Benchmarking String Literal ("") vs Template Literal (``) - using Performance.now()

Muhammad A Faishal - Jul 27 '23 - - Dev Community

Let's talk about String in JavaScript. There are 2 ways developers can define a string:

a. Using String Literal

const str = "Hello " + "world!";
Enter fullscreen mode Exit fullscreen mode

b. Using Template Literal

const worldText = "world!"
const str = `Hello ${worldText}`;
Enter fullscreen mode Exit fullscreen mode

So, have you ever wondered what the difference between the tow? Which one do you usually use? Is the one you're using better?

Let's find out by doing performance test.

Benchmarking

Here are the test case and String Literal and Template Literal used for benchmarking.

Test Case

const iterations = ITERATION_TOTAL // 10, 100, 10000, 1000000
const stringText = 'string'
let text = ''

const start = performance.now()

for (let i = 0; i < iterations; i++) {
  // String or Template literal test case here
}

const end = performance.now()

console.log(`It took ${end - start} ms.`);
Enter fullscreen mode Exit fullscreen mode

String Literal

text = "text"
Enter fullscreen mode Exit fullscreen mode

Template Literal

text = `text`
Enter fullscreen mode Exit fullscreen mode

String Literal concatenating a String

text = "text " + stringText
Enter fullscreen mode Exit fullscreen mode

Template Literal concatenating a String

text = `text ${stringText}`
Enter fullscreen mode Exit fullscreen mode

String Literal concatenating Two Strings

text = stringText + " text " + stringText
Enter fullscreen mode Exit fullscreen mode

Template Literal concatenating Two Strings

text = `${stringText} text ${stringText}`
Enter fullscreen mode Exit fullscreen mode

I ran the tests on Node Js v18.17.0 with different loop iterations: 10, 100, 10,000, 100,000, and 1,000,000. I measured the average times for each iteration.

Result

Here are the results for each iteration (the lower is better):

10 Iterations

String literal & Template literal

100 Iterations

String literal & Template literal

1,000 Iterations

String literal & Template literal

100,000 Iterations

String literal & Template literal

1,000,000 Iterations

String literal & Template literal

Conclusion

It's still good to use both String Literal & Template Literal in simple iteration, displaying a limited items. The results showed a slightly different between the two which is still acceptable.

When dealing with processing large datasets, complex algorithm, generating long strings, using React components that frequently re-render that require a large number of iterations, String Literal is the only one to go.

It's important to understand that not every method is the best fit for every case and project. There might be some trade-offs to consider.

. . . . . . . . . . .
Terabox Video Player