var unicodeString = "가나다라마바사아자차카타파하";
var unicodeString_large = "".padStart(30000, unicodeString);
var textEncoder = new TextEncoder();
const PREFIX_STR = "data:text/plain;base64,";
function toBase64FileReader( text ) {
return new Promise( (resolve, reject) => {
const reader = new FileReader();
// data:text/plain;base64,...
reader.onload = () => resolve(reader.result.substr(PREFIX_STR.length));
reader.onerror = (err) => reject(err);
reader.readAsDataURL(
new Blob([ new TextEncoder().encode( text ) ], { type: "text/plain" })
);
});
}
function toBase64TextEcnder( text ) {
return btoa( String.fromCharCode(textEncoder.encode(text)));
}
function toBase64Unscape( text ) {
return btoa(unescape(encodeURIComponent(text)));
}
toBase64TextEcnder(unicodeString);
toBase64Unscape(unicodeString);
toBase64FileReader(unicodeString);
toBase64TextEcnder(unicodeString_large);
toBase64Unscape(unicodeString_large);
toBase64FileReader(unicodeString_large);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
TextEncoder small (14 chars) | |
unescape small (14 chars) | |
FileReader small (14 chars) | |
TextEncoder large (30,000 chars) | |
unescape large (30,000 chars) | |
FileReader large (30,000 chars) |
Test name | Executions per second |
---|---|
TextEncoder small (14 chars) | 308914.3 Ops/sec |
unescape small (14 chars) | 634181.2 Ops/sec |
FileReader small (14 chars) | 10895.7 Ops/sec |
TextEncoder large (30,000 chars) | 358.7 Ops/sec |
unescape large (30,000 chars) | 800.2 Ops/sec |
FileReader large (30,000 chars) | 2296.8 Ops/sec |
Measuring performance of different approaches to encoding and decoding strings in JavaScript is crucial for optimizing web applications.
Options Compared:
The benchmark tests three approaches:
Pros and Cons of each approach:
Library/Library Purpose:
None of the options used in this benchmark use any external libraries. They are all part of the standard JavaScript API.
Special JS Features/Syntax:
Other Alternatives:
If you need to optimize or compare other encoding and decoding methods, consider the following alternatives:
Keep in mind that each of these alternatives has its own set of advantages, disadvantages, and use cases, so it's essential to choose the most suitable one depending on your specific requirements.