What Comparison Operators Are More Processor Efficient: <, <=, != Or ==?
Solution 1:
Usually, any of them is more efficient than the others. This is because on most CPUs, they map to specialized opcodes, whose execution is handled by the very same physical unit, in slightly different configurations. Using a non-existent but very simple to understand assembly syntax, each branch (if
condition) might translate to:
if (x == 1)
test = x - 1
branch_equal_zero testif (x != 0)
test = 0
branch_non_equal_zero testif (x < 2)
test = x - 2
branch_lower_than_zero testif (x <= 3)
test = x - 3
branch_lower_or_equal_to_zero test
As you can see, comparing to zero (regardless of the comparision) might be faster because there is no subtraction involved -- but faster of such a tiny fraction of second you might notice it only under extremely heavy load.
Even if we are speaking of interpreted languages (PHP and JS), the answer does not change, because all operators are directly mapped to the underlying native comparisions by the interpreters. Let alone any type cast or intermediate conversion that might take place.
Solution 2:
The simple answer is "They are all the same", because, at the basic level, they are all the same. Also, they are all so blazingly fast, you won't notice the difference anyway.
I can see how one may be quicker than the other - CPUs tend to reorder instructions and predict branches - so in specific cases there may be a difference.
However, none if these cases applies to anything you do in JavaScript. In JavaScript you can be very certain they are all the same.
Solution 3:
Let's put it differently, starting from the higher level. Javascript and PHP, both of them are high level language, and so won't use CPU directly but over many processes already thought to optimize what you write. In Javascript that "process" is called Javascript Engine. In PHP it is the interpreter itself. Don't misunderstand me, they are thought to do their work leaving "a bit" of care on optimization.
So in the end the real way to optimize this kind of operation would be to find a real big issue in PHP or Javascript Engine itself.
Now let's face the lowest aspect of these operators. A modern CPU has 3.2GHz (or even more) clock speed. So, it would mean 3200000000 operations per second, which is a huge number. Suppose those operation (which in the end are almost all the same) use 2 or 3 ticks. it would take you about 10^9 operators to notice a significative difference.
Post a Comment for "What Comparison Operators Are More Processor Efficient: <, <=, != Or ==?"