Hacker News new | ask | show | jobs
by chrismandelics 1342 days ago
Plain JS numeric code _can_ be really fast if you stick to typed arrays.

I tried the posted JS in Chrome on an aging thinkpad and each `testSort()` took as long as 125 seconds (32 seconds in Firefox). But when I replaced `Array` with `Float32Array` the runtime dropped to under 7 seconds (about 2 seconds in Firefox) -- in line with the wasm alternatives. Going further and filling an `Int32Array` with `(Math.random() * 2.0 - 1.0) * 100` (as in the AssemblyScript code) brought the Chrome runtime down to around 1.6 sec (still around 2 seconds in Firefox).

2 comments

Also worth noting: default JS `Array.sort()` converts everything to strings and compares them lexically -- so 80 comes before 9. It's a little faster to sort them as numbers: `.sort((a, b) => a - b)` takes me around 40 seconds in Chrome (11 seconds in Firefox).
Thanks man, this is gold.