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() | |
template literal | |
gato |
Test name | Executions per second |
---|---|
String() | 3509922.0 Ops/sec |
.toString() | 3527494.2 Ops/sec |
template literal | 1042908.8 Ops/sec |
gato | 3500685.8 Ops/sec |
The benchmark you're analyzing compares various approaches to convert a number to a string in JavaScript. Specifically, it evaluates the performance of four different methods:
String()
Constructor.toString()
MethodString(num)
:
String
constructor to convert the number. num.toString()
:
toString
method of the number object. String()
, as it's directly tied to the number instance.String()
for someone unfamiliar with methods in JavaScript, and can fail for null
or undefined
, throwing an error.Template Literals (${num}
):
String
constructor or toString()
, but this concern is mitigated by its performance and readability.Concatenation with an Empty String ('' + num
):
The benchmark results show the number of executions per second for each method in the Chrome 130 environment on a Windows platform:
.toString()
: 1,372,328 executions/secString()
Constructor: 102,193 executions/sec (slowest)Readability vs. Performance: While performance is essential, code maintainability and readability should also be considered. String(num)
and .toString()
may be more familiar to developers, while template literals and concatenation may require some initial learning.
Context of Use: The choice may depend on the context in which the conversion is used. For instance, if a number conversion is done frequently in a hot code path, the performance difference would become more relevant.
Browser-specific Performance: The performance results could vary across different browsers and JavaScript engines, so testing in the target environment is advisable.
In conclusion, for most use cases, template literals or concatenation are optimal choices for converting numbers to strings in JavaScript, balancing performance and readability effectively.