So today I encountered this scenario. I had an integer and a string I needed to compare. In order to compare the two I would either have to toString() the integer, or parse the string to an int.
Here’s my question, which one should I go for, is there any difference in performance for the two? (even if it is minimal) Is there a rule of thumb?
Here’s a code example:
var intI = 1;
var stringS = '1';
if (intI.toString() == stringS)
console.log('are equal');
//Or
if (intI == parseInt(stringS))
console.log('are equal');
It would be best if I could declare the Integer as a string I know (as it is not used for calculations). But it is used everywhere on the site.
It depends on the semantics you want more than performance. Should the string “001” be equal to the numeric value
1? If the answer is “yes”, you should convert the values to numbers. If not, then you should compare as strings.Don’t worry about performance of such trivial things unless you’ve got an application that’s doing millions of such operations.
Also note that
parseInt()does not care whether a string of digits has trailing garbage at the end. That isis
true.