function randomCharCodes(n) {
const arr = new Uint8Array(n);
for(let i=0;i<n;i++) {
arr[i] = ~~(Math.random()*0x100)
}
return arr;
}
const chars1 = randomCharCodes(1024*1024);
var chars = chars1;
function test1(arr) {
const l = arr.length;
var i = 0;
var s = "";
for(;i<l;i++){
s+=String.fromCharCode(arr[i]);
}
return s;
}
function test2(arr) {
return String.fromCharCode.apply(null, arr);
}
function test3(arr) {
const l = arr.length;
var i = 0;
var a = [];
for(;i<l;i++){
a[i]=String.fromCharCode(arr[i]);
}
return a.join("");
}
var t1 = test1(chars);
var t2 = test2(chars);
var t3 = test3(chars);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
For-loop | |
String.fromCharCode.apply | |
join method |
Test name | Executions per second |
---|---|
For-loop | 4.3 Ops/sec |
String.fromCharCode.apply | 0.0 Ops/sec |
join method | 5.3 Ops/sec |
This benchmark on MeasureThat.net tests three different methods of converting an array of Unicode character codes into a single string in JavaScript.
Let's break down each approach:
1. for
loop: This classic method iterates through the array of character codes and uses String.fromCharCode(arr[i])
to convert each code into its corresponding character, concatenating them into a final string.
2. String.fromCharCode.apply
: This method utilizes the built-in apply
function to efficiently convert an array of character codes into a string in a single operation.
for
loop approach due to reduced function calls.for
loop.3. join()
method: This method first constructs an array of strings, each corresponding to a character code converted by String.fromCharCode()
, and then uses the join("")
method to concatenate those strings into a single string.
apply
.Alternatives:
Libraries like Lodash or Underscore: These libraries often provide optimized string manipulation functions that might be faster than the built-in methods.
WebAssembly: For highly performance-critical scenarios, you could consider implementing the conversion logic in WebAssembly, which can execute code significantly faster than JavaScript.
Important Note: The benchmark results presented are specific to a particular environment (Chrome 81 on Mac OS X 10.14.6). Performance can vary considerably depending on factors like browser, operating system, hardware, and the size of the input array. Always test benchmarks in your target environment for accurate results.