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([], 20); }
makeTestData().toString()
JSON.stringify(makeTestData());
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
toString | |
JSON.stringify |
Test name | Executions per second |
---|---|
toString | 1053039.6 Ops/sec |
JSON.stringify | 866768.5 Ops/sec |
Let's dive into the explanation of the provided benchmark.
Benchmark Definition
The benchmark is defined by two test cases:
makeTestData().toString()
JSON.stringify(makeTestData())
These two test cases are designed to measure the performance difference between using toString()
and JSON.stringify()
on an array created by the makeTestData()
function.
makeTestData()
Function
The makeTestData()
function generates a large array of 20 random integers, each ranging from 0 to 255. The function is recursive, pushing new random numbers onto the array until it reaches the desired length.
Options Compared
Two options are compared:
toString()
: Converts the generated array into a string using the toString()
method.JSON.stringify()
: Converts the generated array into a JSON string using the JSON.stringify()
method.Pros and Cons of Each Approach
toString()
: This approach is lightweight, as it only requires converting an array to a string. However:JSON.stringify()
: This approach converts the entire array into a JSON string. Its pros are:toString()
, as it handles non-string values correctly.Library and Purpose
The JSON
library is used in this benchmark to provide the JSON.stringify()
method. The purpose of this library is to enable secure, reliable data interchange between web servers and web browsers.
Special JS Feature or Syntax (None)
There are no special JavaScript features or syntax used in this benchmark.
Other Alternatives
If you wanted to test other options, some alternatives could be:
Array.prototype.join()
instead of toString()
Math.random()
)JSON.parse()
+ JSON.stringify()
, or using a library like lodash
)Keep in mind that these alternatives would require additional modifications to the benchmark code.