开发者

PHP - Check variable or compare string?

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 that is not the point here. So, in summary, is a variable check with isset 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 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜