jonschlinkert / is-primitive

Is the typeof value a javascript primitive?
MIT License
37 stars 9 forks source link

Micro-optimization: Changed switch to ifs, added benchmarks #5

Closed rodenmonte closed 6 years ago

rodenmonte commented 6 years ago

This is slightly faster than the switch-case. Here's the test results, just you know they got ran:

  isPrimitive
    ✓ should return true when primitive value
    ✓ should return false when not primitive value

  2 passing (9ms)

Benchmarks are slightly faster. The differences are statistically significant according to benchmark. No offense taken if you decide that the switch-case is elegant enough to prefer over a tiny speed increase. Here's the benchmarks for visibility:

is-primitive$ node bench.js
if x 2,548,250 ops/sec ±0.88% (88 runs sampled)
switch x 2,458,255 ops/sec ±0.74% (87 runs sampled)
object x 1,502,915 ops/sec ±0.89% (84 runs sampled)
object - in x 1,725,589 ops/sec ±0.86% (87 runs sampled)
object - own x 1,870,078 ops/sec ±0.87% (84 runs sampled)
array x 1,172,632 ops/sec ±0.73% (86 runs sampled)
equals x 2,397,364 ops/sec ±0.62% (87 runs sampled)
Fastest is if
rodenmonte commented 6 years ago

NOTE: From a few benchmarks on my own machine, this implementation is at least as fast as https://github.com/jonschlinkert/is-primitive/pull/2/files, although I'm not sure why that method is not faster -- Looks like it's doing fewer comparisons.

pRTwoMethod x 2,531,482 ops/sec ±0.64% (86 runs sampled)
if x 2,549,438 ops/sec ±0.79% (88 runs sampled)
switch x 2,455,527 ops/sec ±0.80% (87 runs sampled)

I did not get different results in terms of order after running the benchmark 8 times, although sometimes the benchmark concluded there was not a significant difference between pRTwoMethod and if.