jonschlinkert / arr-flatten

Recursively flatten an array or arrays. This is the fastest implementation of array flatten.
https://github.com/jonschlinkert
MIT License
59 stars 16 forks source link

Improve Speed #3

Closed lukeed closed 7 years ago

lukeed commented 7 years ago

Hey there,

As strange as it may sound, as long as a len and i are eagerly defined, for-loops always outperform while-loops.

I was going to release (yet another!) flatten lib, but then I saw that our implementations were nearly the same, so a PR makes more sense 😉

Here are the benchmarks from my machine --- ran a few times to verify:

Benchmarking: (3 of 3)
 · med
 · small-med
 · small

# benchmark/fixtures/med.js (586 bytes)
  arr-flatten-0.1.0 (do-while) x 19,975 ops/sec ±0.17% (95 runs sampled)
  arr-flatten-0.2.0 x 322,662 ops/sec ±0.71% (91 runs sampled)
  arr-flatten-1.0.1 x 336,477 ops/sec ±0.47% (93 runs sampled)
  arr-flatten-mine x 345,996 ops/sec ±0.48% (95 runs sampled)

  fastest is arr-flatten-mine

# benchmark/fixtures/small-med.js (161 bytes)
  arr-flatten-0.1.0 (do-while) x 72,826 ops/sec ±0.58% (95 runs sampled)
  arr-flatten-0.2.0 x 1,265,543 ops/sec ±0.56% (96 runs sampled)
  arr-flatten-1.0.1 x 1,341,199 ops/sec ±0.72% (92 runs sampled)
  arr-flatten-mine x 1,398,921 ops/sec ±0.53% (94 runs sampled)

  fastest is arr-flatten-mine

# benchmark/fixtures/small.js (56 bytes)
  arr-flatten-0.1.0 (do-while) x 384,413 ops/sec ±0.63% (94 runs sampled)
  arr-flatten-0.2.0 x 4,653,617 ops/sec ±0.56% (93 runs sampled)
  arr-flatten-1.0.1 x 4,745,099 ops/sec ±0.56% (94 runs sampled)
  arr-flatten-mine x 4,859,175 ops/sec ±0.53% (95 runs sampled)

  fastest is arr-flatten-mine
jonschlinkert commented 7 years ago

As strange as it may sound, as long as a len and i are eagerly defined, for-loops always outperform while-loops.

Looks like that's true in this case, but no, not always. I do benchmarks quite often, and I see while loops outperform for loops just as often. It also changes from time to time when optimizations are made in v8, so don't get to comfortable with your favorite :)

thanks for the pr!

lukeed commented 7 years ago

Oh yeah, not sure why I said "always"

It happens a lot, but definitely not across the board.

Thanks! 🎉