Blogger Information
Blog 20
fans 0
comment 0
visits 19642
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
PHP提高in_array查找元素的方法
大鱼
Original
795 people have browsed it

<?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;}?>

run time:7003.6449432373ms

我们可以先使用array_flip进行键值互换,然后使用isset方法来判断元素是否存在,这样可以提高效率。

<?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;}?>

run time:2.2781620025635ms


Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post