Most programming languages have some kind of parsing or casting a string to an integer. In javascript the parseInt(str) function will convert a string to an integer (number type). Here are a few ways to do it starting from the fastest to the slowest.

Double Tilde (Bitwise Not Operator) - Fastest

~~"1";

Multiplication by 1 - Faster

"1" * 1;

Using the Known parseInt Function - Slowest

parseInt("1");

Of course, this test was performed on the latest Chrome version 38 which means it should be comparable to Node.js (V8 engine).

For the skeptics, run the test on jsperf.com that Jonathan Petitcolas wrote. Very cool. Sadly I've been abusing the parseInt all along.


comments powered by Disqus
eXTReMe Tracker