Created
January 29, 2018 22:46
-
-
Save swashcap/1835c553201517dd170aa23bdc65a1db to your computer and use it in GitHub Desktop.
Testing for the fastest JS string checks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
}) | |
Author
swashcap
commented
Jan 29, 2018
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment