From ea6db33a7d3d8923feb89f221785d0b4ed913f48 Mon Sep 17 00:00:00 2001 From: Greg Hurrell Date: Sat, 1 Aug 2015 23:19:05 -0700 Subject: [PATCH] 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. --- src/addDigits.js | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) 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]; } -- 2.37.1