What is more efficient
if ($n-1 < $x)
or
if ($n <= $x)
Anyone know开发者_C百科?
Negligible difference, but if ($n <= $x)
is much clearer.
Probably ($n <= $x)
since there's one less operation (no subtraction). However, this is only equivalent for integers and the difference is very likely insignificant.
It shouldn't be significant speed gain but later seems more readable to me. The first one has an extra subtraction part too.
In the first instance you're performing two operations (subtract then compare) whereas in the second you're performing just one (compare). I think it's safe to say the second is more performant. Regardless, the first form is very nonstandard and I don't know why it would ever be used as a substitute for the second.
Neither. PHP has no enforced implementation saying weather it's bytecode, interpreted directly from the AST, or compiled to machine code. In fact, there are a billion different implementations and the main one probably changes all the time just like the rest of the language and API.
Even at the assembly level in x86, there is no difference between the two operations. Proof:
x < y
cmp eax, y
jb its_true
x <= y
cmp eax, y
jbe its_true
JBE
is a synonym to something like JC
IIRC, which just checks a single flag. Both of these conditional branches simply check if a flag is set or not.
The only real way these operations could effect speed is you could overload both less than/greater than operators and equality, and even then the speed difference should be negligible.
Since you're using a high-level scripting language, it's not a matter of processor operations to perform that action. More time will be spent in parsing the code, validating variable types and managing variables memory and many other things.
Even if there's no practical difference, I guess the second will be faster since the language expression is simpler.
The term $n-1 is in a section more complex to understand that <=. The math operator has only a few options (>, <, <=, ==, >=, !=, ...), but the term $n-1 requires a more complex analysis because it has to be split by the minus sign at first, and then analyzed both parts (which could also be a function call, a constant, a variable, another complex expression, ...)
精彩评论