Browse Source

Merge pull request #341 from MStoykov/stringConcatOptimization

Simplify ascii string concat and skip some allocations
Dmitry Panov 3 years ago
parent
commit
4739a1d10a
2 changed files with 17 additions and 4 deletions
  1. 1 4
      string_ascii.go
  2. 16 0
      string_test.go

+ 1 - 4
string_ascii.go

@@ -247,10 +247,7 @@ func (s asciiString) length() int {
 func (s asciiString) concat(other valueString) valueString {
 func (s asciiString) concat(other valueString) valueString {
 	switch other := other.(type) {
 	switch other := other.(type) {
 	case asciiString:
 	case asciiString:
-		b := make([]byte, len(s)+len(other))
-		copy(b, s)
-		copy(b[len(s):], other)
-		return asciiString(b)
+		return asciiString(s + other)
 	case unicodeString:
 	case unicodeString:
 		b := make([]uint16, len(s)+len(other))
 		b := make([]uint16, len(s)+len(other))
 		b[0] = unistring.BOM
 		b[0] = unistring.BOM

+ 16 - 0
string_test.go

@@ -12,3 +12,19 @@ func TestStringOOBProperties(t *testing.T) {
 
 
 	testScript1(SCRIPT, valueInt(1), t)
 	testScript1(SCRIPT, valueInt(1), t)
 }
 }
+
+func BenchmarkASCIIConcat(b *testing.B) {
+	vm := New()
+
+	b.ResetTimer()
+	b.ReportAllocs()
+	for i := 0; i < b.N; i++ {
+		_, err := vm.RunString(`{let result = "ab";
+		for (let i = 0 ; i < 10;i++) {
+			result += result;
+		}}`)
+		if err != nil {
+			b.Fatalf("Unexpected errors %s", err)
+		}
+	}
+}