JavaScript CharAt() Runtime
What is the runtime complexity of the charAt() function in JavaScript with respect to the string length? Is it defined in EcmaScript (I failed to find it)? If not, what's the behav
Solution 1:
Here is a small experiment: I generate texts of different lengths and perform charAt
a million times.
function repeat(text, n) {
const randomPositions = [];
for (let i = 0; i < n; i++) {
randomPositions.push(Math.floor(Math.random() * text.length));
}
const t0 = performance.now();
for (let pos of randomPositions) {
text.charAt(pos);
}
console.log("Elapsed time: " + (performance.now() - t0) + " ms")
}
const characters ='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
// Thanks https://www.programiz.com/javascript/examples/generate-random-strings
function generateString(length) {
let result = '';
const charactersLength = characters.length;
for (let i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
[10**2, 10**3, 10**4, 10**5, 10**6, 10**7].forEach(l => repeat(generateString(l), 10000000));
I run it in Chrome 91, Firefox 89 and Safari 14.
Results:
In Chrome and Firefox, the needed time does not seem to correlate very strongly with the text length indicating O(1). Some example times:
# Chrome:
Elapsed time: 37.40000003576279 ms
Elapsed time: 39.5 ms
Elapsed time: 38.30000001192093 ms
Elapsed time: 39.40000003576279 ms
Elapsed time: 46.39999997615814 ms
Elapsed time: 45.89999997615814 ms
# Firefox
Elapsed time: 255 ms
Elapsed time: 224 ms
Elapsed time: 269 ms
Elapsed time: 227 ms
Elapsed time: 424 ms
Elapsed time: 393 ms
In Safari, the needed time goes up:
Elapsed time: 94.00000000005821 ms
Elapsed time: 83.0000000000291 ms
Elapsed time: 93 ms
Elapsed time: 128 ms
Elapsed time: 294 ms
Elapsed time: 571 ms
Did I miss an important factor? Please let me know!
Post a Comment for "JavaScript CharAt() Runtime"