While writing some code that needs to be as performant as possible, I came across this question about charAt vs startsWith, but then realized it applied specifically to Java. After running some tests on jsperf.com, I found my answer. See below.
While writing some code that needs to be as performant as possible, I came across this question about charAt vs startsWith, but then realized it applied specifically to Java. After running some tests on jsperf.com, I found my answer. See below.
In Chrome 102, startsWith is faster than charAt. [0] is somewhere in the middle.
You can view the perf.link test here. Below are the results I got testing in Chrome Version 102.0.5005.115 (Official Build) (arm64) / macOS Monterey Version 12.4:
Setup code:
const strs = [
'',
'*',
'#',
'*short',
'#short',
'*'.padEnd(2500, '-'),
'#'.padEnd(2500, '-'),
]
startsWith
strs.forEach(str => str.startsWith('*'))
// 1,521,590 ops/s
// fastest
charAt
strs.forEach(str => str.charAt(0) === '*')
// 1,060,830 ops/s
[0]
strs.forEach(str => str[0] === '*')
// 1,294,190 ops/s