× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

JS - If condition with only 1 else, does checking order affect performance?

Utkarsh Upadhyay
Jun 30, 2015
<p><strong>Short answer:</strong> No, it does not effect the computation time.</p> <p><strong>Long answer:</strong> Most Javascript engines (Spider Monkey and V8) internally use a <a href="https://en.wikipedia.org/wiki/Just-in-time_compilation" rel="nofollow">Just in Time compiler</a> which will iron over those differences during runtime.</p> <p>In low level programming languages (read: C/C++ and the ilk), you <em>may</em> gain something if you are able to prevent <a href="https://en.wikipedia.org/wiki/Branch_predictor" rel="nofollow">branch mis-predicts</a>, like in <a href="http://stackoverflow.com/questions/11227809/why-is-processing-a-sorted-array-faster-than-an-unsorted-array">C++ code</a>, but the gain is usually worth it only if you are doing Kernel programming or doing extreme micro-optimizations.</p> <hr> <p>Theoretically, whether it makes a difference or not depends on what kind of compiler you are looking at. If you are looking at a compiler which can learn from code traces, e.g. a Just in Time compiler, then it will make a difference if a certain pocket of code is the hot spot or not. If you are looking at static compilers, it may mean that the compiler <em>may</em> use one less clock cycle in one of the cases (either <code>if</code> or <code>else</code>) by preventing a <code>jmp</code>, but it'll depend on the compiler implementation.</p> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/31097315/JS%20-%20If%20condition%20with%20only%201%20else,%20does%20checking%20order%20affect%20performance?/31097354">Stack Overflow</a>.</p>
comments powered by Disqus