0

In JavaScript codes, I have seen people using '+' character to convert string to integer as in -

var i = +"2";

another way is just using parseInt() method as following -

var i = parseInt("2");

I want to know which one is efficient?

Sorry I should also add that, I am dealing with integers only and the data is huge so even a little difference in performance would be good for me.

5
  • 1
    Use JSPerf website, if you really care.
    – Amadan
    Jan 29, 2013 at 6:36
  • 1
    Stylistically, parseInt is more "efficient" as it will most likely save you more time on debugging Jan 29, 2013 at 6:36
  • 1
    First it would depend on which browser your are using. Also, why don't use just write a timing test. Jan 29, 2013 at 6:37
  • There's no conclusive answer, so go with what reads best. Also +"1.2" doesn't return an integer.
    – Ja͢ck
    Jan 29, 2013 at 6:44
  • 2
    Just did a quick timing test and found out - in firefox(latest) '+' is run almost two times faster than parseInt, but in chrome(latest) and IE9 '+' is slightly slower than parseInt. Jan 29, 2013 at 6:50

2 Answers 2

2

It depends on the Browser.

i've created a nasty little Testcase for some String-To-Number conversion possibilities i know.

Ive also added possibilities to convert to floating-point-numbers, as in Javascript Numbers are Numbers, no matter if they have floating point or not.

Check it out. Corrections and suggestions appreciated!

As some other folks around here said in the comments below the question: I also think its better not to think to much about it, bu to focus on readability..

2

Long story short, don't worry about it, use whatever is more convinient for you and the actual case; micro-optimizations like this are useless. Id' say just remember that you might need to pass in the radix parameter into parseInt if your number is (or looks) octal or some other format.

1
  • Actually, only one option truly converts to an integer :)
    – Ja͢ck
    Jan 29, 2013 at 6:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.