Introduction
Conversions in Javascript

Conversions in Javascript

Using Javascript has an ease, you can achieve the same result by doing it in different ways. Here am going to discuss about the performance implications of the same. Lets start with string to number conversion. The usual way of string to number conversion is done using parseInt. However there are someother ways it can be done as well

 var n1 = parseInt("12"); 
 var n2 = Number("12"); 
 var n3 = +"12"; 
 var n4 = ~~(1*"12");
 

All of the above does the same job and n1==n2==n3==n4. So, of all the ways we have to see which one is the ideal way to do that. This is where performance is a big consideration. In this jsperf test we can see which one performs well. Of four of them the last wicked way performs well in all browsers except chrome and safari webkit browsers(I don’t know why). At the end the best way is to use the parseInt, somebody might prefer using +”Value” for ease of typing. However should know the performance benefits of the other ways. Similarly, string conversion

 var date = new Date(); 
 var ds = date.toString(); 
 var dr = date+"";

In this case ds==dr, the way toString works is faster in most cases.

Author

Vetrichelvan Jeyapalpandy

12 years of experience in web development. Javascript enthusiast. Performance is an important trait of any website, so trying to improve that wherever possible.

View Comments
Next Post

Image Compression and CSS Sprites - Web Developer Tools

Previous Post

Brain Effing Javascript