PHP提高in_array查找元素的方法

PHP提高in_array查找元素的方法
<pre>
<?php
$arr = array();

// 创建10万个元素的数组
for($i=0; $i<100000; $i++){
$arr[] = $i;
}

// 记录开始时间
$starttime = getMicrotime();

// 随机创建10000个数字使用in_array比较
for($j=0; $j<10000; $j++){
$str = mt_rand(1,99999);
in_array($str, $arr);
}

// 记录结束时间
$endtime = getMicrotime();

echo 'run time:'.(float)(($endtime-$starttime)*1000).'ms<br>';

/**
* 获取microtime
* @return float
*/
function getMicrotime(){
list($usec, $sec) = explode(' ', microtime());
return (float)$usec + (float)$sec;
}
?>
</pre>
run time:7003.6449432373ms


我们可以先使用array_flip进行键值互换,然后使用isset方法来判断元素是否存在,这样可以提高效率。
<pre>
<?php
$arr = array();

// 创建10万个元素的数组
for($i=0; $i<100000; $i++){
$arr[] = $i;
}

// 键值互换
$arr = array_flip($arr);

// 记录开始时间
$starttime = getMicrotime();

// 随机创建1000个数字使用isset比较
for($j=0; $j<1000; $j++){
$str = mt_rand(1,99999);
isset($arr[$str]);
}


// 记录结束时间
$endtime = getMicrotime();

echo 'run time:'.(float)(($endtime-$starttime)*1000).'ms<br>';

/**
* 获取microtime
* @return float
*/
function getMicrotime(){
list($usec, $sec) = explode(' ', microtime());
return (float)$usec + (float)$sec;
}
?>
</pre>
run time:2.2781620025635ms

posted @ 2019-11-15 10:31  newmiracle宇宙  阅读(126)  评论(0编辑  收藏  举报