var element = document.createElement('div');
var value = 42;
element.setAttribute('id', String(value));
element.setAttribute('id', '' + value);
element.setAttribute('id', `${value}`);
element.setAttribute('id', value.toString());
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Constructor | |
Concat | |
Template | |
toString |
Test name | Executions per second |
---|---|
Constructor | 5996818.5 Ops/sec |
Concat | 8745031.0 Ops/sec |
Template | 8764941.0 Ops/sec |
toString | 8747081.0 Ops/sec |
Let's break down the provided benchmark and explain what's being tested, compared, and their pros/cons.
Benchmark Definition JSON
The provided JSON defines a benchmark named "Set number value as string attribute". It consists of two parts:
var element = document.createElement('div');
) before running the actual test.element
created in the script preparation code is not inserted into any HTML document.Test Cases
There are four individual test cases:
element.setAttribute('id', String(value));
.element.setAttribute('id', '' + value);
.element.setAttribute('id',
${value});
.element.setAttribute('id', value.toString());
.What's being tested
These test cases measure the performance of different ways to convert a number (value
) into a string attribute for an HTML element.
Comparison
The tests compare the execution time (in executions per second) of each method:
String()
function constructor.+
) to concatenate the string ' '
with the value.toString()
method.Pros and Cons
Here's a brief summary of each approach:
toString()
.toString()
is the slowest method, as it creates an unnecessary string object.Library
There is no external library used in this benchmark. The tests only rely on built-in JavaScript features.
Special JS Feature or Syntax
String()
function constructor is an older feature that was also introduced in ES5. It's still widely used and supported.Alternatives
If you want to benchmark similar scenarios or explore other string conversion methods, here are some alternatives:
Keep in mind that these alternatives may not be directly related to converting a number to a string attribute, but they can still provide valuable insights into JavaScript's performance characteristics.