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++) {
new TextEncoder().encode(randomStrings.join('')).length
}
var j = 0;
for (let i = 0; i < iterations; i++) {
new Blob([randomStrings.join('')]).size
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Blob | |
TextEncoder |
Test name | Executions per second |
---|---|
Blob | 47.4 Ops/sec |
TextEncoder | 9.0 Ops/sec |
Let's dive into the Benchmark Definition and test cases.
Benchmark Definition
The benchmark measures the performance difference between encoding a large string using TextEncoder
(Blob) and creating a Blob from the same string.
Script Preparation Code
The script preparation code generates an array of random strings, stores them in the variable randomStrings
, and creates a new instance of TextEncoder
.
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();
Html Preparation Code
There is no HTML preparation code provided.
Test Cases
The benchmark consists of two test cases:
TextEncoder
( Blob).for (let i = 0; i < iterations; i++) {
new TextEncoder().encode(randomStrings.join('')).length
}
for (let i = 0; i < iterations; i++) {
new Blob([randomStrings.join('')]).size
}
Options being compared
The two test cases are comparing:
TextEncoder
(Blob) vs. creating a Blob from the same string.Pros and Cons of each approach:
Library: TextEncoder
The TextEncoder
library provides an optimized way to encode strings in JavaScript. It's designed to be fast and efficient, making it suitable for encoding large amounts of data. The library uses a optimized algorithm that takes into account the specifics of the string being encoded, such as its length and character set.
Special JS feature: Blob
The Blob
object is a modern JavaScript feature that represents a binary file or data blob. When used in conjunction with TextEncoder
, it provides an efficient way to encode strings by converting them into a format that can be easily processed by web browsers and other applications.
Other alternatives:
utf-8
or utf-16
, which provide optimized encoding algorithms for text data.FileReader
or FileSaver
, which provide APIs for working with files and blobs in JavaScript.