From: Greg Hurrell Date: Sun, 2 Aug 2015 06:19:05 +0000 (-0700) Subject: Massive speed-up by avoiding Chrome de-opt in hottest function X-Git-Url: https://git.wincent.com/hextrapolate.git/commitdiff_plain/ea6db33a7d3d8923feb89f221785d0b4ed913f48 Massive speed-up by avoiding Chrome de-opt in hottest function I became suspicious of the Math calls thanks to this thread: https://groups.google.com/forum/#!msg/google-chrome-developer-tools/Y0J2XQ9iiqU/H60qqZNlQa8J Turns out, those were the culprit. --- diff --git a/src/addDigits.js b/src/addDigits.js index 4a3de34..27d998e 100644 --- a/src/addDigits.js +++ b/src/addDigits.js @@ -14,16 +14,15 @@ export default function addDigits( ): Array { let result = []; let carry = 0; - for ( - let i = 0, max = Math.max(aDigits.length, bDigits.length); - i < max || carry; - i++ - ) { - const aDigit = aDigits[i] || 0; - const bDigit = bDigits[i] || 0; + for (let i = 0; i < aDigits.length || i < bDigits.length || carry; i++) { + const aDigit = i < aDigits.length ? aDigits[i] : 0; + const bDigit = i < bDigits.length ? bDigits[i] : 0; const sum = aDigit + bDigit + carry; result.push(sum % base); - carry = Math.floor(sum / base); + + // ~~ here is the equivalent of Math.floor; used to avoid V8 de-opt, + // "Reference to a variable which requires dynamic lookup". + carry = ~~(sum / base); } return result.length ? result : [0]; }