var point = {
name : "1",
x : 1,
y : 2
}
`<br/>${point.name}: ${point.x}, ${point.y}`
'<br/>' +' '+point.name +' : '+point.x+' , '+ point.y
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Interpolation | |
Contatenation |
Test name | Executions per second |
---|---|
Interpolation | 5132759.0 Ops/sec |
Contatenation | 5187108.5 Ops/sec |
Let's break down the provided benchmark and explain what's being tested, compared options, pros and cons of each approach, and other considerations.
What is being tested?
The benchmark tests two different ways to create strings in JavaScript:
${...}
syntax) to insert values into a string.+
operator to concatenate strings together.Options compared:
${...}
)+
operator)Pros and Cons of each approach:
Template Literals (Interpolation)
Pros:
Cons:
String Concatenation
Pros:
Cons:
1 + 2 + 'hello'
would evaluate to '123hello'
, not 'hello23'
)Other considerations:
Now, let's look at the specific test cases:
Test Case 1: Interpolation
The benchmark uses template literals to create a simple HTML string with interpolation. The Benchmark Definition
JSON contains a single template literal expression:
`<br/>${point.name}: ${point.x}, ${point.y}`
This code will insert the values of point.name
, point.x
, and point.y
into the resulting string.
Test Case 2: Concatenation
The second test case uses the +
operator to concatenate strings:
' '<br/> '+' point.name +' : '+point.x+' , '+ point.y
This code concatenates four separate strings together, using the +
operator for each step.
Library and syntax:
There is no external library used in this benchmark. The template literal syntax (${...}
) is a built-in JavaScript feature introduced in ES6.
If you're interested in exploring other alternatives or more complex scenarios, some possible options include:
String.prototype.replace()
method with a function to create interpolated strings