<!--your preparation HTML code goes here-->
const slug = '1234567890';
for (let i = 0; i < 1000000; i++) {
const url = `/${slug}.html`;
}
for (let i = 0; i < 1000000; i++) {
const url = '/' + slug + '.html';
}
for (let i = 0; i < 1000000; i++) {
const url = ['/', slug, '.html'].join('');
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Template Literal | |
String Concatenation | |
Array.join() |
Test name | Executions per second |
---|---|
Template Literal | 401.9 Ops/sec |
String Concatenation | 602.9 Ops/sec |
Array.join() | 18.7 Ops/sec |
The benchmark is designed to measure and compare the performance of two different string manipulation approaches in JavaScript: Template Literals and String Concatenation.
Template Literals
for (let i = 0; i < 1000000; i++) {
const url = `/${slug}.html`;
}
). It allows for embedded expressions and multi-line strings. In this case, it constructs a URL string using a variable
slug` placed within the template literal.String Concatenation
for (let i = 0; i < 1000000; i++) {
const url = '/' + slug + '.html';
}
+
operator. It constructs the same URL by concatenating the string segments manually.From the benchmark results:
String Concatenation:
Template Literal:
Pros:
${expression}
) without additional operators.Cons:
Pros:
Cons:
In addition to the two methods tested, there are other alternatives for string manipulation in JavaScript:
Array .join()
method: You can use the .join()
method, which utilizes arrays to construct strings. This is particularly useful when concatenating a large number of strings.
Example:
const url = ['/', slug, '.html'].join('');
StringBuilder pattern: Using libraries that implement a StringBuilder pattern can be beneficial in scenarios requiring extensive string manipulations, especially to avoid continuous reallocation of string memory.
Using external libraries: Libraries like lodash provide functions for handling strings efficiently. However, they often come with overhead due to the additional library size and abstraction.
The benchmark provides valuable insights into string manipulation efficiencies in JavaScript, specifically comparing template literals and string concatenation. Depending on the performance needs and use case complexity, developers can make informed decisions about which approach to adopt. The results emphasize the need to balance readability and performance while considering broader context for real-world applications.