Reputation: 1068
So what if we tell a programming language to calculate this: X/1, where X is any number. Do they actually calculate the output or check/ignore 1 and return X?
Furthermore, when coding something like the above is it worth checking if the divider is 1 or is it faster to just let it compute the division anyway?
Thank you
In order to elaborate on this question: Which is faster?
$result = $number / $divisor;
or
$result = $divisor > 1 ? $number / $divisor : $number;
Upvotes: 3
Views: 144
Reputation: 10248
Comparing the examples (at least for PHP):
<?php
$divisor = 1;
for ($i=0; $i<100000000; $i ++ ) {
if ($divisor != 1)
$a = $i / $divisor;
else
$a = $i;
}
takes 6.9s
on my machine. The other one:
<?php
$divisor = 1;
for ($i=0; $i<100000000; $i ++ ) {
$a = $i / $divisor;
}
takes only 5.2s
So to answer the final question, which one is faster: just let it compute the division :-)
Upvotes: 2
Reputation: 101
Since a check and a jump + the actual division would be more cpu instructions than just doing the division, I'm pretty certain that it will just be done.
If your code is variable / 1 (the 1 being static) the compiler will most likely optimize it away.
Upvotes: 0
Reputation: 4094
Most programming languages will probably not check for special divisors (with the exception of 0).
CPUs are very fast at division nowadays so it's not worth checking beforehand. The checks could take longer than the actual division.
Upvotes: 2