RequestPolicy/tractest — Issue #232: Optimize boolean returns [eg isAllowed...() functions]
Author: jsamuel
Created: 2011-12-22 02:48:13+00:00
State: open
Labels: extension

Benchmarking different ways to return a boolean from an exists test (again using http://benchmarkjs.com):
{{{
// Static setup
var v=1;
var r;

// Benchmark ?:
return v ? true : false;

// Benchmark &&true
return v && true;

// Benchmark !!
return !!v;

// Benchmark if[return]else[return]
if (v) return true;
else return false;

// Benchmark if[return]return
if (v) return true;
return false;

// Benchmark r-if[v]r-return
r=false;
if (v) r=true;
return r;
}}}
Results (v=1 -- true):
{{{
?: x 193,359,909 ops/sec ±0.41% (67 runs sampled)
&&true x 193,597,803 ops/sec ±0.39% (63 runs sampled)
!! x 226,615,870 ops/sec ±0.32% (69 runs sampled)
if[return]else[return] x 193,251,534 ops/sec ±0.36% (63 runs sampled)
if[return]return x 193,254,640 ops/sec ±0.41% (70 runs sampled)
r-if[v]r-return x 156,658,641 ops/sec ±0.29% (71 runs sampled)
Fastest is !!
}}}
Results (v=0 -- false):
{{{
?: x 192,544,165 ops/sec ±0.68% (64 runs sampled)
&&true x 193,357,127 ops/sec ±0.42% (61 runs sampled)
!! x 226,279,260 ops/sec ±0.41% (66 runs sampled)
if[return]else[return] x 193,256,943 ops/sec ±0.32% (67 runs sampled)
if[return]return x 193,169,757 ops/sec ±0.35% (64 runs sampled)
r-if[v]r-return x 165,388,908 ops/sec ±0.31% (62 runs sampled)
Fastest is !!
}}}

Conclusion: !! value to boolean conversion is much faster than the currently implemented ?: method.