let num = 500;
let nums = [];
for(let i = 0; i < 100; ++i) {
nums.push(String(num));
}
let num = 500;
let nums = [];
for(let i = 0; i < 100; ++i) {
nums.push(num.toString());
}
let num = 500;
let nums = [];
for(let i = 0; i < 100; ++i) {
nums.push(''+num);
}
let num = 500;
let nums = [];
for(let i = 0; i < 100; ++i) {
nums.push(`${num}`);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
String() | |
.toString() | |
Concatenation | |
Template string |
Test name | Executions per second |
---|---|
String() | 498177.4 Ops/sec |
.toString() | 973399.9 Ops/sec |
Concatenation | 3251532.8 Ops/sec |
Template string | 3309127.8 Ops/sec |
Let's break down the provided benchmark and explain what's being tested, compared, and the pros/cons of each approach.
Benchmark Overview
The benchmark compares four different methods for converting an integer to a string:
String()
.toString()
'' + num
)${num}
)These methods are used in a loop to generate 100 elements, and the execution speed is measured.
Library Usage
None of the benchmark definitions explicitly use any external libraries. However, it's worth noting that String()
and .toString()
are built-in JavaScript methods, while concatenation and template strings may work differently across browsers or versions.
Special JS Features/Syntax
Template strings (${num}
) were introduced in ECMAScript 2015 (ES6). They allow for a more readable way of interpolating variables into string templates. The '' + num
approach is an older way of concatenating strings using the "+" operator.
Benchmark Results
The benchmark results show that:
${num}
) perform the fastest, with an average execution speed of 2374346 executions per second.'' + num
) comes in second, with an average execution speed of 2358853.75 executions per second..toString()
performs slower than concatenation, with an average execution speed of 803412.5625 executions per second.String()
performs the slowest, with an average execution speed of 66786.21875 executions per second.Pros/Cons of Each Approach
Here's a brief summary:
${num}
):'' + num
):.toString()
**:String()
**:Alternatives
Other alternatives for converting integers to strings include:
parseInt(num.toString())
or parseFloat(num.toString())
, which can lead to performance issues if not done correctly.toString()
method, but this would add external dependency and is generally unnecessary.In conclusion, template strings (${num}
) are the most efficient way of converting integers to strings in JavaScript, followed by concatenation ('' + num
). The .toString()
and String()
methods perform significantly slower.