Why does this function run faster with long numbers than short numbers?

I wrote a JS perf to show that parsing the digits in a number via magnitude reduction is faster than by string evaluation (for a sorting task). What I found though is that the magnitude reduction algorithm performs operations faster for longer numbers (not per digit, but in total), even though it should loop more times for those longer numbers. It happens in Chrome, Safari and Firefox on OS X (haven't tested other OSs).

Any Idea what's going on here?

Here's the perf: http://jsperf.com/get-digits-from-integer

Edit Here's a perf that shows the differences with varying numbers of digits 8, 16, 32, 64, and 128. Only the 8-digit number is slower than expected, at 16-digits, the performance slows down as the numbers get longer. http://jsperf.com/get-digits-from-integer/3

and here's the function in question:

function getDigitsByMagnitudeReduction(num){
  var digits = [];
  while (num > 0){
    digits.push(num % 10);
    num = (num / 10) >> 0;
  }
  return digits.reverse();
}

Before checking the performance of a function, you should check that it actually returns the correct result.

You are using >> 0 to truncate a number to an integer. The bitwise operations work with 32 bits numbers, so the function will only work with numbers up to 21474836479 .

If you use num = Math.floor((num / 10)); it will work with larger numbers, but the precision of numbers in JavaScript is limited to 15-17 digits, so neither the result for 91827766102983847569298376298387839 nor for 91882759110292883726299387440027766102983847569298376298387839 will be correct.

链接地址: http://www.djcxy.com/p/64172.html

上一篇: 在DataTable中查找值

下一篇: 为什么这个函数在长数字比短数字更快运行?