given $b is a random int number from $a to $c... so which method more faster?
1.
Code: Select all
foreach ($a .. $c) { return 1 if $_ == int($b) }
2.
Code: Select all
return 1 if $a <= $b && $b <= $c
thanx in advance
Moderator: Moderators
Code: Select all
foreach ($a .. $c) { return 1 if $_ == int($b) }
Code: Select all
return 1 if $a <= $b && $b <= $c
sli wrote:I hate to say something like this to a fellow staff member, but... If you really have to ask, you need to work on your programming fundamentals. Loops will always be slower. Allow me to explain:
The second one is a single if-statement, but the loop will run exactly $b times before returning. So if $a is 1, $b is 9999, and $c is 10000, the loop will run 9,999 times before terminating. That said, I highly doubt the difference will be noticeable unless you expect $c to be a large number at any point. The second one is more readable as well.
kali wrote:So I guess the second line runs exactly twice (once if you can do short circuiting half of the time, if $b is indeed a random number between $a and $c) while the first runs in constant time $b.