DEV Community

Discussion on: Daily Challenge #287 - 16+18=214

Collapse
 
qm3ster profile image
Mihail Malo • Edited

You already did the skimming, but you could also avoid stringification altogether: dev.to/qm3ster/comment/14en6

Collapse
 
willsmart profile image
willsmart

Thanks, that's a fair point. Here's the tweaked code:

function piecewiseAdd_numeric(addendA: number, addendB: number) : number {
  let sum = 0, cursor = 1;
  while (addendA || addendB) {
    const digitSum = (addendA % 10) + (addendB % 10);
    sum += cursor * digitSum;
    cursor *= digitSum < 10 ? 10 : 100;
    addendA = Math.floor(addendA / 10);
    addendB = Math.floor(addendB / 10);
  }
  return sum;
}

Benchmark here -- numeric method has it by a nose most of the time you run it, sometimes a bit more. For smaller inputs they're pretty much even.

In C or Rust or something closer to the metal Mihail's post is definitely the way to go (imo).
In JS strings are pretty quick and numbers are surprisingly slow to deal with (there's no support for integers, etc) and I find the language doesn't really reward that kind of close-knit optimization, so I felt it wasn't worth the additional complication.

Thread Thread
 
qm3ster profile image
Mihail Malo

I wonder what the result with asm.js would be.
There are some claims that in the process of implementing asm.js V8 in particular just optimized normal code to the speed of corresponding asm.js, but some extra assertions might still help?