function moreData(arr, left) {
if(left === 0) return arr;
else {
arr.push(Math.floor(Math.random() * 256));
return moreData(arr, left - 1);
}
}
function makeTestData() { return moreData([], 4); }
makeTestData().map(i => `${i}`).join('-')
JSON.stringify(makeTestData());
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
map + join | |
JSON.stringify |
Test name | Executions per second |
---|---|
map + join | 50080.1 Ops/sec |
JSON.stringify | 47216.2 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
Benchmark Definition JSON
The provided JSON represents a benchmark definition, which is essentially a script that creates test data and defines how it should be used for the benchmark. In this case, we have two benchmark definitions:
makeTestData()
: This function generates test data by recursively pushing random numbers to an array using the moreData
function.makeTestData()
as input and applies two operations: map
and join
. The map
function applies a transformation to each element in the array, while the join
method concatenates all elements into a single string separated by a hyphen.Options Compared
The two benchmark definitions compare two different approaches to concatenate an array of numbers:
JSON.stringify()
: This is a built-in JavaScript method that converts a value (in this case, an array) to a JSON string.map
+ join
: This approach uses the map
function to transform each number in the array into a string and then concatenates these strings using the join
method.Pros and Cons
Here are some pros and cons of each approach:
JSON.stringify()
Pros:
JSON.stringify()
is generally faster than the map
+ join
approach.Cons:
map
+ join
Pros:
map
.Cons:
map
and join
), which might be slower than calling JSON.stringify()
.Library Used
There is no explicit library used in this benchmark definition. However, it's worth noting that if you were to use a library like Lodash or Ramda for functional programming, you might choose to use their map
and join
functions to achieve similar results.
Special JS Feature/Syntax
There are no special JavaScript features or syntaxes used in this benchmark definition. The code only uses standard JavaScript functions (push
, concat
) and data types (arrays, strings).
Other Alternatives
If you want to explore other alternatives for concatenating an array of numbers, here are a few options:
map
+ join
: This approach would be slower than the current benchmark but might be more readable.lodash
or ramda
with their string-joining functions: These libraries provide efficient and flexible ways to concatenate arrays into strings.Keep in mind that these alternatives might not change the overall performance of your application, but they can affect readability and maintainability.