码迷,mamicode.com
首页 > 其他好文 > 详细

判断元素是否存时,使用isset会比in_array快得多

时间:2018-01-26 10:52:25      阅读:291      评论:0      收藏:0      [点我收藏+]

标签:set   存在   end   很多   补充   art   body   gpo   sse   

情境

有时候,我们需要判断一个元素是否存在于已有数据中(以此来获得非重复值),这时候,使用isset来判断会比in_array快得多很多!!

 

测试

1)准备测试数据

$exists_a = [];
$exists_b = [];
$check     = [];

for ($i=0,$len=100000; $i<$len; $i++)
{
    $check[] = $i;
}

for ($i=0,$len=10000; $i<$len; $i++)
{
    $rnd            = round(0,100000);
    $exists_a[]     = $rnd;
    $exists_b[$rnd] = 1;
}

2)使用in_array做判断验证

$result     = [];
$start_time = microtime(true);
foreach ($check as $key => $value)
{
    if (!in_array($value, $exists_a))
    {
        $result[] = $value;
    }
}
$end_time = microtime(true);
echo ‘使用in_array验证元素是否存在耗时:‘ . ($end_time - $start_time), ‘秒<hr/>‘;

结果:// 使用in_array验证元素是否存在耗时:10.537812948227秒

3)使用isset做判断验证

$result     = [];
$start_time = microtime(true);
foreach ($check as $key => $value)
{
    if (!isset($exists_b[$value]))
    {
        $result[] = $value;
    }
}
$end_time = microtime(true);
echo ‘使用isset验证元素是否存在耗时:‘ . ($end_time - $start_

结果:// 使用isset验证元素是否存在耗时:0.018424034118652秒

 

补充

使用 array_key_exists 判断

<?php
$exists = [];
$check     = [];

for ($i=0,$len=100000; $i<$len; $i++)
{
    $check[] = $i;
}

for ($i=0,$len=10000; $i<$len; $i++)
{
    $rnd          = round(0,100000);
    $exists[$rnd] = $rnd;
}

$result     = [];
$start_time = microtime(true);
foreach ($check as $key => $value)
{
    if (array_key_exists($value, $exists))
    {
        $result[] = $value;
    }
}
$end_time = microtime(true);
echo ‘使用array_key_exists验证元素是否存在耗时:‘ . ($end_time - $start_time), ‘秒<hr/>‘;
?>

结果:// 使用array_key_exists验证元素是否存在耗时:0.022138833999634秒

 

总结

尽量少用in_array,isset 和 array_key_exists 会比 in_array 快得多很多!!

判断元素是否存时,使用isset会比in_array快得多

标签:set   存在   end   很多   补充   art   body   gpo   sse   

原文地址:https://www.cnblogs.com/tujia/p/8358099.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!