views:

66

answers:

1

Hi,

I wonder which of these excerpts should take less resources, when we want to see if "word" is an element of an array:

Excerpt 1 - Check variable:

<?php
function checkWord($word, $elements) {
    $array = array($word => true);
    foreach ($elements as $element) {
        if (isset($array[$element])) return true;
    }
    return false;
}

$elements = array('this', 'is', 'an', 'array', 'with', 'a', 'word');
checkWord('word', $elements);
?>

Excerpt 2 - Compare string:

<?php
function checkWord($word, $elements) {
    foreach ($elements as $element) {
        if ($element == $word) return true;
    }
    return false;
}

$elements = array('this', 'is', 'an', 'array', 'with', 'a', 'word');
checkWord('word', $elements);
?>

I know we could simply use in_array(), but it would only work for this case.
The question here is for when we have to explode lines of a file, or any other situation that we don't have the $element so easily.
So, resuming, is a variable check better than comparing strings?

EDIT Please understand that I know there are better ways of doing this. I am just asking which of the ways above is better and takes less resources. I assume that checking variables do not compare strings and it's instant, while comparing string should be slower. Am I correct?

Thank you!

+1  A: 

I did a benchmarking test with a 51000+ unique words list to satisfy your (and mine, to be honest) curiosity. Although not by much, using isset() is indeed faster than comparing strings, with an average of 0.0144901275634765625 seconds for the first method vs 0.0164241790771484375 seconds for the second method, out of 5 tries.

Hope this helps.

FreekOne
I said above we could use that function. That is not the question here.
Nuno Peralta
I have realized that after I posted, my apologies ! Please see the updated answer.
FreekOne
Yeah, thank you for answering the question, and for understanding the purpose of it (I assume you were the only one, to be honest...). Anyway, do these tests help me to decide what is the best for CPU? Thank you once more!
Nuno Peralta
Glad to be of help ! Actually, this tests only shows that the difference between the methods is negligible, and the fastest method remains `in_array()` @ 0.003899097442626953125 seconds on the mentioned data set. Rather than using alternative methods, I would process the data set in such a way that the built-in method can be used on it, but if for whatever freak reason this is not possible, I would obviously go for the fastest remaining method which in this case is the first one. In the end, it depends mostly on your given data set.
FreekOne
Ok thank you :) Yeah, I usually rely on built-in functions. Also, I don't really use foreach when I can simply avoid it (because it duplicates the array), so it can also be slowing the tests here :) Anyway, as I was expecting, isset() is better than string compare!
Nuno Peralta