Skip to content Skip to sidebar Skip to footer

Is Subtracting Zero Some Sort Of Javascript Performance Trick?

Looking in the jQuery core I found the following code convention: nth: function(elem, i, match){ return match[3] - 0 === i; }, And I was really curious about the snippet match

Solution 1:

Probably just a short-hand way to force the left-hand side into integer. Not as clear as calling a function, of course.

This tutorial on type-conversion states:

Any mathematical operator except the concatenation/addition operator will force type-conversion. So conversion of a string to a number might entail performing a mathematical operation on the string representation of the number that would not affect the resulting number, such as subtracting zero or multiplying by one.

This also reveals that "subtracting" is a better search term than "minus". :)

Solution 2:

Various ways to coerse JS strings to numbers, and their consequences:

Results of converting various strings using the above techniques(source: phrogz.net)

I personally use *1 as it is short to type, but still stands out (unlike the unary +), and either gives me what the user typed or fails completely. I only use parseInt() when I know that there will be non-numeric content at the end to ignore, or when I need to parse a non-base-10 string.

Solution 3:

Just a info, According to this site

using unary + operator is faster one than any of the following (which include '- 0'):

var numValue = stringValue - 0;
/* or */var numValue = stringValue * 1;
/* or */var numValue = stringValue / 1;

unary + operator also type-converts its operand to a number and because it does not do any additional mathematical operations it is the fastest method for type-converting a string into a number.

This contradicts James' benchmark, although he may be might be correct. I think jQuery wouldn't utilise this syntax if it were slow.

Solution 4:

Your main reason to use this syntax is if you have generic code that may be any number (int or float) and you want to do a type-sensitive compare (===)

Solution 5:

If it's not an old relic that got lost, then it just tries to change the type to Number.

Post a Comment for "Is Subtracting Zero Some Sort Of Javascript Performance Trick?"