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 快得多很多!!

  • 相关阅读:
    1 基本概念 进入java世界
    一文了解kudu【转载】
    jenkins git项目clean before checkout 和 wipe out repository & force clone
    jenkins 内置判断条件
    jenkins常用插件使用说明-git publisher
    常用正则表达式
    基于ldap+sentry+rbac的hive数据库权限测试
    nginx_mirror_module流量复制在项目中的应用
    jenkins上job误删除怎么恢复
    pipeline语法学习日记
  • 原文地址:https://www.cnblogs.com/tujia/p/8358099.html
Copyright © 2011-2022 走看看