Heim  >  Artikel  >  php教程  >  如何快速判断一个值是否在数组中

如何快速判断一个值是否在数组中

WBOY
WBOYOriginal
2016-06-06 20:12:072588Durchsuche

?php$s = '';for($i=1;$i=1000000;$i++){$r = rand(1000000,9999999);$s .= $r.',';}$a = explode(',',$s);$t1 =microtime(true);for($i=0;$i100;$i++){$t = rand(1,1000000);if(in_array($a[$t],$a)){}}$t2 = microtime(true);$b = array_flip($a);for($i=0

<?php $s = '';
for($i=1;$i<=1000000;$i++){
$r = rand(1000000,9999999);
$s .= $r.',';
}
$a = explode(',',$s);
$t1 =microtime(true);
for($i=0;$i<100;$i++){
$t = rand(1,1000000);
if(in_array($a[$t],$a)){}
}
$t2 = microtime(true);
$b = array_flip($a);
for($i=0;$i<100;$i++){
$t = rand(1,1000000);
if(isset($a[$t],$b)){}
}
$t3 = microtime(true);
$c = array_flip($a);
for($i=0;$i<100;$i++){
$t = rand(1,1000000);
if(array_key_exists($a[$t],$c)){}
}
$t4 = microtime(true);
echo $t2-$t1;
echo "\r\n";
echo $t3-$t2;
echo "\r\n";
echo $t4-$t3;
echo "\r\n";

time php -f test.php 运行结果如下

8.6652669906616
0.43561315536499
0.67533493041992

real?? ?0m14.255s
user?? ?0m11.990s
sys?? ?0m0.380s

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn