I was just trying to see the performance difference in using || (double pipes, short-circuit operator, which should be faster) instead of |.
But the result gave no insight to the actual performance improvements. If we just reorder the below codes..to execute console log with | first, then it will show more time than the other.
How can I see the performance difference using this or any other way? Also,
Can somebody explain why there is difference when we change the order?
If
performance.now();behaves like this, I don't see any point in using it.
Please help. Thanks :)
var t3 = performance.now();
console.log(1 | (1),
1 || (0),
1 || (-1),
1 || ("a string"),
1 || (""),
1 || (null),
1 || (undefined),
1 || (console.log(3)),
1 || (Infinity))
var t4 = performance.now();
console.log("Call with (double) '||' took " + (t4 - t3) + " milliseconds.");
var t0 = performance.now();
console.log(1 | (1),
1 | (0),
1 | (-1),
1 | ("a string"),
1 | (""),
1 | (null),
1 | (undefined),
1 | (console.log(3)),
1 | (Infinity))
var t1 = performance.now();
console.log("Call with single | took " + (t1 - t0) + " milliseconds.");
console.log) need initialisation, which will be done the first time it is used, which can easily disrupt the measured performance by several orders of magnitude.|vs||, then don't includeconsole.login the block that is being timed.Some demonstrations:
Run the following code a couple of times. Observe that:
Also observe that I/O has a horrendous effect on performance: (you'll need to scroll down)
Taking all that into account, let's write a test case that tests your operations:
Note that pretty much all of the time it takes the
|case to complete is still coming fromconsole.log, proving only that short-circuiting on||truly works. Now of course this is accurate for|vs||operations that actually involve I/O. If you leave that out however, the results are much close together again:(Note that I cranked up the for loop to 10 million, proving just how much time
console.logactually takes!)And in spite of all of that,
|and||do entirely different things. Not only in terms of execution, but also in terms of the result. Try1 || 126vs1 | 126, or"a" || "b"vs"a" | "b".