Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Testing for the fastest JS string checks
var hrtime = process.hrtime;
function checkForProp (a) {
return !!a.toLowerCase
}
function checkToStringEqual (a) {
return a.toString() === a
}
function checkTypeof (a) {
return typeof a === 'string'
}
function checkTypeofLoose (a) {
return typeof a == 'string'
}
function checkStringEqual (a) {
return '' + a === a
}
var tests = [checkTypeofLoose, checkForProp, checkToStringEqual, checkTypeof, checkStringEqual]
var testStr = 'string'
var count = 10000
tests.forEach((t) => {
const start = hrtime()
for (let i = 0; i < count; i++) {
t(testStr)
}
const end = hrtime()
console.log(t.name, (end[1] - start[1]) / 1000)
})
@swashcap

This comment has been minimized.

Copy link
Owner Author

commented Jan 29, 2018

$ node --version
v8.9.4
$ node string-check-performance.js
checkTypeofLoose 304.529
checkForProp 385.314
checkToStringEqual 1748.515
checkTypeof 1677.513
checkStringEqual 282.735
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.