Benchmarking String Literal (“”) vs Template Literal (“) – using Performance.now()

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

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

a. Using String Literal

const str = "Hello " + "world!";

b. Using Template Literal

const worldText = "world!"
const str = `Hello ${worldText}`;

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.`);

String Literal

text = "text"

Template Literal

text = `text`

String Literal concatenating a String

text = "text " + stringText

Template Literal concatenating a String

text = `text ${stringText}`

String Literal concatenating Two Strings

text = stringText + " text " + stringText

Template Literal concatenating Two Strings

text = `${stringText} text ${stringText}`

I ran the tests on Node Js v18.17.0 with different loop iterations: 10, 100, 10,000, 100,000, and 1000,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.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these <abbr title="HyperText Markup Language">HTML</abbr> tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>