Skip to content

Instantly share code, notes, and snippets.

@swashcap
Created January 29, 2018 22:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save swashcap/1835c553201517dd170aa23bdc65a1db to your computer and use it in GitHub Desktop.
Save swashcap/1835c553201517dd170aa23bdc65a1db to your computer and use it in GitHub Desktop.
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
Copy link
Author

$ 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