Usually while sorting you do:
if (x < y) return -1
else if (x > y) return 1
else return 0
or
return ((x > y) ? 1 : ((x < y)) ? -1 : 0))
Two comparisons for what seems can be accomplished with only one. In assembly all you have to do is subtract both to a register, check if is negative, check if is zero. The problem is in javascript if we were to subtract:
var sub = (x - y);
return (sub == 0 ? 0 : ((sub < 0) ? -1 : 1))
This would end up with even more code to be executed.
So, some questions:
- Is there a way of simplifying or speedying this in javascript?
- Can compiled javascript interpretors like chrome’s optimize this kind of comparison?
- What about other languages?
In Javascript,
sortdoes not have to return-1,0or1. It can return any number. This means that you only need to subtract one number from the other to compare them.The MDC docs for
Array.sortsuggest this implementation: