zoukankan      html  css  js  c++  java
  • 判断元素是否存时,使用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 快得多很多!!

  • 相关阅读:
    hdu 2647 Reward
    hdu 2094 产生冠军
    hdu 3342 Legal or Not
    hdu 1285 确定比赛名次
    hdu 3006 The Number of set
    hdu 1429 胜利大逃亡(续)
    UVA 146 ID Codes
    UVA 131 The Psychic Poker Player
    洛谷 P2491消防 解题报告
    洛谷 P2587 [ZJOI2008]泡泡堂 解题报告
  • 原文地址:https://www.cnblogs.com/tujia/p/8358099.html
Copyright © 2011-2022 走看看