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("base64")
encodeURIComponent(JSON.stringify(makeTestData()));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
to base64 string | |
json stringify |
Test name | Executions per second |
---|---|
to base64 string | 968414.5 Ops/sec |
json stringify | 799541.6 Ops/sec |
Let's break down the benchmark and explain what's being tested, compared, and other considerations.
Benchmark Overview
The benchmark is designed to compare two approaches for encoding data in JavaScript:
base64
function to encode the data.encodeURIComponent
function to convert the encoded data into a URL-safe format.Script Preparation Code
The script preparation code generates test data by recursively pushing random numbers onto an array, starting from index 0, and then converts this array to a base64 string using the makeTestData()
function. The generated test data is then used to create two benchmark definitions: one for encoding the data as a URL-safe base64 string, and another for encoding it using JSON.stringify with encodeURIComponent.
Library
The base64
function is not explicitly mentioned in the code, but it's likely that this is an external library or built-in function. In modern JavaScript, the btoa()
(binary to ASCII) function can be used to achieve similar results.
Special JS Feature/Syntax
There are no special JavaScript features or syntax used in this benchmark, apart from the use of JSON.stringify
, which is a standard JavaScript method for converting objects into strings.
Comparison Options
The two comparison options are:
Other Considerations
When choosing between these two approaches, consider the following factors:
Other Alternatives
If you're interested in exploring other alternatives, here are a few options:
Buffer
class to encode and decode binary data.Keep in mind that each of these alternatives has its own trade-offs and considerations, so be sure to evaluate them carefully before making a decision.