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 arrayBuffer = new ArrayBuffer(iterations*1000);
var buffer = new Uint8Array(arrayBuffer);
var j = 0;
for (let i = 0; i < iterations; i++) {
var str = randomStrings[i % iterations];
buffer[j] = str.length;
var res = encoder.encodeInto(str, buffer.subarray(j+1));
j = j + res.written;
}
var stringMap = {};
var counter = 0;
function stringToMap(s) {
var i = stringMap[s];
if (i === undefined) {
stringMap[s] = counter++;
} else {
return i;
}
}
var j = 0;
for (let i = 0; i < iterations; i++) {
var str = randomStrings[i % iterations];
var num = stringToMap(str);
buffer[j] = num;
j = j + 8;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Baseline encoder | |
baseline hash |
Test name | Executions per second |
---|---|
Baseline encoder | 8036.6 Ops/sec |
baseline hash | 11038.6 Ops/sec |
Benchmark Overview
The provided JSON represents a benchmark test case for comparing the performance of TextEncoder
in JavaScript with two alternative approaches: hashing a string using a custom map and simply encoding the string.
Test Case 1: Baseline Encoder
This test case uses the TextEncoder
to encode the length of a random string into an array buffer. The encoder is used to encode each character of the string, and the written bytes are stored in the buffer.
Pros:
TextEncoder
in encoding strings.Cons:
Test Case 2: Baseline Hash
This test case uses a custom map to hash the length of a random string. The map is used to store the length of each string, and the hashed value is stored in an array buffer.
Pros:
Cons:
TextEncoder
usage.Other Considerations
Library: TextEncoder
TextEncoder
is a built-in JavaScript function that encodes a string into an array of bytes, suitable for storing in a buffer or transmitting over a network. The encodeInto()
method takes two arguments: the string to encode and the buffer to write the encoded data into.
Special JS Feature/ Syntax: None
There are no special JavaScript features or syntax used in this benchmark test case that would require additional explanation.
Alternatives
Other approaches for testing the performance of encoding strings include:
Overall, this benchmark test case provides a simple and straightforward way to compare the performance of TextEncoder
with two alternative approaches. However, it's worth noting that real-world use cases may involve additional considerations such as buffer size, data type, and encoding scheme, which are not addressed in this benchmark.