var dataShort = rand();
var dataLong = Array.from({ length: 100 }, rand).join("\n");
function rand() {
return Math.random().toString(36);
}
btoa(dataShort);
btoa(dataLong);
JSON.stringify(dataShort);
JSON.stringify(dataLong);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
base64 short string | |
base64 long string | |
json short string | |
json long string |
Test name | Executions per second |
---|---|
base64 short string | 5109587.5 Ops/sec |
base64 long string | 778427.6 Ops/sec |
json short string | 10003633.0 Ops/sec |
json long string | 353215.2 Ops/sec |
Benchmark Overview
The MeasureThat.net website allows users to create and run JavaScript microbenchmarks. The provided benchmark compares the execution times of two methods: btoa
(base64 encoding) and JSON.stringify
. These methods are used to encode data in a compact binary format.
Test Cases
There are four test cases:
btoa(dataShort)
btoa(dataLong)
JSON.stringify(dataShort)
JSON.stringify(dataLong)
Options Compared
The benchmark compares two encoding methods:
Pros and Cons of Each Approach
Base64 (btoa)
Pros:
Cons:
JSON.stringify
Pros:
Cons:
Library Used
In this benchmark, btoa
uses the Web API's built-in base64 encoding function.
Special JS Feature or Syntax
There are no special JavaScript features or syntaxes used in this benchmark. The code only employs standard JavaScript constructs like variables, strings, and functions.
Other Alternatives
If you're looking for alternative encoding methods, consider:
utf8-escape
or base64-js
, which provide more control over the encoding process.Example Use Cases
Base64 encoding is commonly used in scenarios like:
JSON.stringify is often used for: