关于这个帖子what is faster: in_array or isset?他们同意isset比in_array快。
但我遇到的问题是我的页面加载速度太慢而且我var_dump-ed我的vars明确测试它。
这是我提取的数组。
$items = array(66, 68, 9, 68, 66, 57, 57, 66, 66, 66, 66, 68, 66, 48, 49, 14, 55, 57, 49, 105, 57, 57, 48, 105, 57, 66, 67, 57, 97, 67, 67, 50, 68, 57, 50, 51, 69, 71, 57, 57, 67, 69, 50, 50, 68, 67, 68, 68, 45, 97, 57, 56, 69, 69, 50, 67, 14, 68, 52, 53, 56, 62, 96, 96, 54, 62, 62, 68, 71, 69, 98, 83, 57, 98, 56, 84, 54, 6, 63, 64, 64, 62, 63, 54, 63, 54, 84, 1, 64, 64, 84, 54, 84, 84, 14, 3, 90, 65, 15, 15, 15, 63, 15, 93, 90, 90, 96, 93, 34, 94, 34, 74, 13, 40, 74, 40, 93, 93, 93, 93, 95, 94, 36, 35, 41, 94, 94, 35, 36, 41, 42, 44, 42, 93, 93, 96, 93, 36, 569, 43, 44, 65, 35, 13, 17, 33, 7, 7, 7, 7, 8, 73, 10, 12, 1, 1, 12, 1, 12, 38, 32, 39, 79, 80, 16, 82, 72, 82, 81, 72, 82, 18, 81, 28, 27, 27, 5, 26, 27, 25, 18, 26, 20, 26, 27, 28, 31, 20, 24, 28, 27, 20, 30, 29, 23, 22, 22, 29, 22, 30, 23, 23, 48, 49, 22, 29, 20, 30, 23, 18, 25, 31, 24, 28, 27, 26, 50, 57, 15, 62, 66, 63, 67, 64, 68, 65, 69, 34, 36, 35, 13, 14, 1, 3, 103, 74, 72, 81, 82, 90, 93, 94, 95, 96, 97, 98, 20, 25, 34, 36, 35, 8, 81, 73, 99, 100, 101, 102, 103, 104, 568, 568);
$productIds = array();
我得到的结果恰恰相反,其中:
$start = microtime(true);
foreach ($items as $item)
{
//if (!in_array($item, $productIds)) // 0.00030207633972168 seconds
if(!isset($productIds[$item])) // 5.2928924560547E-5 seconds
{
$productIds[] = $item;
}
}
$end = microtime(true);
echo ($end - $start).' seconds';
当然,在这种情况下我会坚持使用in_array。但我只是好奇这里发生了什么......任何想法?
修改(实际代码)
public function validateCreation ()
{
if ($this->getRequestParameter('ccItems'))
{
$arrProductIds = array();
foreach ($this->getRequestParameter('ccItems') as $ccItem)
{
//if ((!is_null($ccItem["product_id"])) && !isset($arrProductIds[$ccItem["product_id"]])) // 12.758,9kb-1.194ms and 12.758,9kb-1.202ms
if ((!is_null($ccItem["product_id"])) && !in_array($ccItem["product_id"], $arrProductIds)) // 11.599,5kb-972ms and 11.599.5kb-959ms
{
$arrProductIds[] = $ccItem["product_id"];
}
}
$result = "";
if (count($arrProductIds) > 0)
{
$isRequestValidated = MyClass::StaticFunction($arrProductIds, $result);
if ($isRequestValidated === false)
{
$this->getRequest()->setError('overall_error', $result);
}
}
}
return !($this->getRequest()->hasErrors());
}
答案 0 :(得分:0)
你错了。
in_array
需要 0.00030207633972168 秒isset
需要 5.2928924560547E-5 秒。请注意最后的 E-5 ,按照惯例, 5.2928924560547×10 -5 = 0.000052928924560547 ,这更快。