Skip to content

Instantly share code, notes, and snippets.

@kurtroberts
Last active July 3, 2018 14:53
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 kurtroberts/8d4d6718514b2f5d9e16 to your computer and use it in GitHub Desktop.
Save kurtroberts/8d4d6718514b2f5d9e16 to your computer and use it in GitHub Desktop.
Understanding Integers and Performance in JS

Understanding Integers and Performance in JS

This is just an interactive node session, not really a code snippet.

But it's pretty instructive.

Implicit Casting

kroberts-macpro:~ kroberts$ node
> 23|0
23
> "23"|0
23
> parseInt("23")
23
> 23.33333|0
23
> "23 cats"
'23 cats'
> "23 cats"|0
0
> parseInt("23 cats")
23
> parseInt("cat");
NaN
> "cat"|0
0

Performance

> console.time('parseInt'); for (var i = 0; i < 10000000; i++) { parseInt('23'); };console.timeEnd('parseInt');
parseInt: 211ms
> console.time('or'); for (var i = 0; i < 10000000; i++) { '23'|0; };console.timeEnd('or');
or: 34ms
> console.time('parseInt'); for (var i = 0; i < 10000000; i++) { parseInt('23'); };console.timeEnd('parseInt');
parseInt: 233ms
> console.time('or'); for (var i = 0; i < 10000000; i++) { '23'|0; };console.timeEnd('or');
or: 33ms
> console.time('parseInt'); for (var i = 0; i < 10000000; i++) { parseInt('23'); };console.timeEnd('parseInt');
parseInt: 232ms
> console.time('or'); for (var i = 0; i < 10000000; i++) { '23'|0; };console.timeEnd('or');
or: 32ms
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment