0

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.

ghoti
  • 45,319
  • 8
  • 65
  • 104
Andrew
  • 1,431
  • 2
  • 16
  • 18
  • why go through the hassle of getting even numbers? what's the purpose of doing so? just find them directly! – Joseph Mar 07 '12 at 04:03

4 Answers4

1

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.

Community
  • 1
  • 1
S.P.
  • 3,054
  • 1
  • 19
  • 17
0

The second is much faster. For processing like this, assume the computation time is negligible, and that the number of trials, rather, will more greatly affect your speed. That's how it almost always is, when it comes to program efficiency. Especially when compared to simple checks, like two if statements versus one.

0

Combine the if statements in the second one for even more speed.

if($count%2==0 && $variable==$line) {
}
judda
  • 3,977
  • 1
  • 25
  • 27
0

I assume you have an array like

$lines = array('bob', '39', 'jack', '22', 'jill', '85');

Then simply skip odd lines in your for loop :

for ($i=0, $len=count($lines); $i<$len; $i+=2) {
   if ($lines[$i] == $var) {
       // true
   }
}
Yanick Rochon
  • 51,409
  • 25
  • 133
  • 214