array_key_exists($ key,$ array)vs!empty($ array [$ key]) [英] array_key_exists($key, $array) vs !empty($array[$key])

查看:149
本文介绍了array_key_exists($ key,$ array)vs!empty($ array [$ key])的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我见过很多人做前者,做一个相对于另一个有什么性能上的好处吗?还是只是一个眼神糖果?我每次都会使用后者,因为它更短并且对我而言更具可读性.

I've seen a lot of people do the former, is there any performance benefit doing one vs the other? Or is it just an eye candy? I personally use the latter every time as it is shorter and personally more readable to me.

推荐答案

其他响应集中在两个函数之间的差异上.的确如此,但是如果源数组不包含null0"",...(空值)值,则可以对两个函数的速度进行基准测试:

The other responses focus on the differences between the two functions. This is true, but if the source array does not contain null or 0 or "", ... (empty values) values you can benchmark the speed of the two functions:

<?php

function makeRandomArray( $length ) {
    $array = array();
    for ($i = 0; $i < $length; $i++) {
        $array[$i] = rand(1, $length);
    }

    return $array;
}

function benchmark( $count, $function ) {
    $start = microtime(true);
    for ($i = 0; $i < $count; $i++) {
        $function();
    }
    return microtime(true) - $start;
}

$runs = 100000;
$smallLength = 10;
$small = makeRandomArray($smallLength);

var_dump(benchmark($runs, function() {
    global $small, $smallLength;
    array_key_exists(rand(0, $smallLength), $small);
}));
var_dump(benchmark($runs, function() {
    global $small, $smallLength;
    !empty($small[rand(0, $smallLength)]);
}));

哪个给了我以下结果:

对于小型阵列:

  • array_key_exists:float(0.18357992172241)
  • empty:float(0.072798013687134)
  • isset:浮动(0.070242881774902)
  • array_key_exists: float(0.18357992172241)
  • empty: float(0.072798013687134)
  • isset: float(0.070242881774902)

对于相对较大的数组:

  • array_key_exists:float(0.57489585876465)
  • empty:浮动(0.0068421363830566)
  • isset:浮动(0.0069410800933838)
  • array_key_exists: float(0.57489585876465)
  • empty: float(0.0068421363830566)
  • isset: float(0.0069410800933838)

因此,如果可能的话,使用emptyisset更快.

So if it's possible it's faster to use empty or isset.

这篇关于array_key_exists($ key,$ array)vs!empty($ array [$ key])的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆