簡體   English   中英

為什么in_array比foreach內部的isset快?

[英]Why is in_array is faster than isset inside foreach?

關於此線程,更快的是:in_array或isset? 他們同意isset比in_array快。

但是我遇到了我的頁面加載速度太慢的問題,我用var_dump-ed我的var對其進行顯式測試。

這是我提取的數組。

$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());
}

你錯了。

  • in_array需要0.00030207633972168
  • isset需要5.2928924560547E-5秒。 注意最后的E-5 ,按照慣例,它意味着5.2928924560547×10 -5 = 0.000052928924560547 ,這更快。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM