I have a text file that serves as a simple database, each entry spanning two lines, like so:
name
number
bob
39
jack
22
jill
85
Now say that I have each line separated in an array, and I wanted to analyze each NAME and see if it equals a variable. Would it be faster to do this:
if($variable == $line) {
//true
}
Or first filter out the even numbered lines (the names), and then analyze them to see if they equal the variable? If you don’t know, the first line following basically finds the remainder of the count (this is all in a foreach loop) divided by 2, and if it equals 0 then it is an even number.
if ($count%2 == 0) {
if($variable == $line) {
//true
}
}
Thanks.
I would definitely go with the first style depending on “some” circumstances. For example how long is your equality operation going to take do you think? In cases where I have seen integers or doubles being compared this first style seemed much better to me personally.
The modulo operator is an expensive operation in my book. If you have a huge database doing the modulo operation will take a lot of time. You can try to make it faster using other methods Reference something like this one.
I hope that you do a time study on the above code and see the timing difference for yourself. I have had some major problems related to time when I have used modulo operations for around 5 million data set.
Editing based on one of the answers.
Definitely use the +=2 operation that has been provided instead of modulo as well as the first case.