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

  • 相关阅读:
    char *详细指针
    UIScrollViewA都PI得知。
    Android动画之二:View Animation
    计算机基本知识拾遗(七)页面缓存数据的同步和恢复机制页
    得到Android系统语言设置
    Harry Potter and the Prisoner of Azkaban
    zerglurker的c语言教程006——第一功能
    ExtJs迄今datefield控制设置默认值
    quick 2.23 它们的定义c++代码lua与总结的一些细节
    uva live 6190 Beautiful Spacing (二分法+dp试 基于优化的独特性质)
  • 原文地址:https://www.cnblogs.com/tujia/p/8358099.html
Copyright © 2011-2022 走看看