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

时间:2023-03-10 07:27:37
判断元素是否存时,使用isset会比in_array快得多

情境

有时候,我们需要判断一个元素是否存在于已有数据中(以此来获得非重复值),这时候,使用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 快得多很多!!