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().toString()
JSON.stringify(makeTestData());
(`${makeTestData()}`);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
toString | |
JSON.stringify | |
template-literals |
Test name | Executions per second |
---|---|
toString | 6534584.0 Ops/sec |
JSON.stringify | 8394936.0 Ops/sec |
template-literals | 5901881.0 Ops/sec |
Let's break down the benchmark and its options.
Benchmark Definition JSON
The benchmark is designed to compare three ways of converting an array to a string in JavaScript:
JSON.stringify()
toString()
method on arraysScript Preparation Code
The script preparation code generates a test data array by recursively pushing random numbers onto the array using the moreData
function. The makeTestData
function returns this generated array.
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); }
Html Preparation Code
There is no HTML preparation code provided.
Individual Test Cases
The benchmark consists of three test cases:
toString
: Converts the generated array to a string using the toString()
method.JSON.stringify
: Converts the generated array to a JSON string using JSON.stringify()
.template-literals
: Converts the generated array to a string using template literals (template strings).Pros and Cons of Each Approach
toString()
: This approach is simple and widely supported, but it can be slow for large arrays because it iterates over each element in the array.JSON.stringify()
: This approach is also straightforward but can be slower than toString()
, especially for large arrays with nested objects or dates. It's also not suitable for all data types (e.g., binary data).) instead of single quotes. They can be faster than
toString()` for large arrays because they don't require iterating over each element.Library: Lodash
The benchmark uses the lodash
library, which is not explicitly mentioned in the JSON definition. However, upon closer inspection, we see that the moreData
function uses push
and Math.random
, which are both part of the standard JavaScript API. But if you were to use a more complex data structure or require additional functions from Lodash, it would be beneficial.
Special JS Feature/Syntax: Arrow Functions
The benchmark uses arrow functions (e.g., return moreData(arr, left - 1)
) which are a feature introduced in ECMAScript 2015. While not specific to the benchmark, understanding arrow functions is useful for working with modern JavaScript code.
Alternatives
If you wanted to modify or add to this benchmark, here are some alternatives: