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];
new TextEncoder().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 | 362.6 Ops/sec |
Blob | 7.3 Ops/sec |
The benchmark provided compares two methods of encoding strings in JavaScript: using the TextEncoder
API and the Blob
constructor. These methods are evaluated on their performance, specifically how many executions can be performed per second for encoding a set of random strings.
Preparation:
TextEncoder
instance is created, which will be used in one of the benchmarking tests.Individual Test Cases:
TextEncoder
API by encoding each random string and returning the length of the encoded result.Blob
object for each random string and then retrieving the size of the Blob
.TextEncoder:
Pros:
Cons:
Blob:
Pros:
Blob
API allows you to construct file-like objects from raw data, useful for web applications dealing with files or binary data.Cons:
TextEncoder
.Blob
involves additional overhead as it creates a wrapper object around the data.The benchmark results show that the performance difference between the two methods is significant. The TextEncoder
can execute around 2366 operations per second, while the Blob
test can only execute about 381 operations per second. This indicates that, for encoding strings, TextEncoder
is more efficient and should be preferred when text encoding is the primary concern.
Use Cases: The choice between TextEncoder
and Blob
often depends on specific use cases in your application. For instance, if you are primarily dealing with text data and need high performance for frequent operations, TextEncoder
is a better choice. On the other hand, if your application handles varied data types (text, images, binaries, etc.), Blob
may suit your needs.
Other Alternatives:
ArrayBuffer
along with typed arrays, which may improve performance for certain scenarios but would require more complex handling, particularly for text.In conclusion, the benchmark highlights the performance difference between two popular methods for encoding strings in JavaScript. For most applications dealing exclusively with text, the TextEncoder
is the preferable option due to its simplicity and efficiency. Conversely, if handling a wider array of data types is necessary, using a Blob
provides the versatility needed despite its lower performance in string encoding tasks.