iterations = 1000;
function randomStringGen(n) {
let strings = [];
for (let i = 0; i < n; i++) {
let s = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
strings[i] = s;
}
return strings;
}
var randomStrings = randomStringGen(iterations);
var encoder = new TextEncoder();
var j = 0;
for (let i = 0; i < iterations; i++) {
var str = randomStrings[i % iterations];
encoder.encode(str).length
}
var j = 0;
for (let i = 0; i < iterations; i++) {
var str = randomStrings[i % iterations];
new Blob([str]).size
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
TextEncoder | |
Blob |
Test name | Executions per second |
---|---|
TextEncoder | 3283.6 Ops/sec |
Blob | 29.5 Ops/sec |
Let's break down the provided benchmark definition and test cases.
What is being tested?
The provided JSON represents a JavaScript microbenchmark that compares two approaches for encoding strings: TextEncoder
and creating a Blob
object from a string.
Options compared:
Two options are compared:
Pros and Cons of each approach:
TextEncoder
Library usage:
In this benchmark, no external libraries are explicitly mentioned. However, the TextEncoder
API is built into modern JavaScript engines and is not considered a third-party library.
Special JS feature or syntax:
The benchmark uses the for...of
loop (in the Html Preparation Code
) to generate an array of random strings, which is a relatively recent feature introduced in ECMAScript 2015. This loop provides a concise way to iterate over arrays and is commonly used in modern JavaScript development.
Other alternatives:
If you need to compare encoding approaches with other options, some alternative methods could be:
Buffer
API (a more low-level, binary-based approach)js-base64
or base64-js
for encoding and decoding stringsKeep in mind that these alternatives may have different pros and cons compared to the TextEncoder
and Blob
approaches.