In hacking on the gRaphaĆ«l code base, I came across a recurring pattern syntax pattern I hadn’t encountered in JavaScript before.
Essentially, instead of using this very common conditional construct:
if (a) b;
The author uses:
!a && b;
Similarly,
if (a) b; else c;
Is written:
!a && b; a && c;
I was curious about the performance difference between the styles, and wrote a benchmark to compare them.
I only tested in WebKit nightly 53415, but I found that in every case, the if / if-else construct outperformed the pure-logic construct. The differences in performance are admittedly negligible, so I’ll be sticking to if-else for readability, and I’ll accept the performance benefit as a happy side-effect.
It’s likely that if statements can actually be slightly slower when block-scope variables are enabled (by enabling JavaScript 1.7+ for a script).
Case 1:
Case 2:
I haven’t profiled this code yet, but I’m going to assume that the latter is faster in JavaScript 1.7 and higher.
April 8th, 2010
Please do let me know if you end up profiling this code.
April 8th, 2010
Duncan, here’s a profiler I whipped up quickly which also includes sharp scope. Surprisingly, sharp scope performed the worst.
April 8th, 2010