If I'm deep in a nest of loops I'm wondering which of these is more efficient:

如果我深陷在一堆循环中,我想知道哪一个更有效:

if (!isset($array[$key])) $array[$key] = $val;

or

$array[$key] = $val;

The second form is much more desirable as far as readable code goes. In reality the names are longer and the array is multidimensional. So the first form ends up looking pretty gnarly in my program.

就可读代码而言,第二种形式更可取。实际上,名称更长,数组是多维的。第一种形式在我的程序中看起来很粗糙。

But I'm wondering if the second form might be slower. Since the code is in one of the most frequently-executed functions in the program, I'd like to use the faster form.

但是我想知道第二种形式会不会慢一些。由于代码位于程序中执行最频繁的函数之一,所以我希望使用更快的形式。

Generally speaking this code will execute many times with the same value of "$key". So in most cases $array[$key] will already be set, and the isset() will return FALSE.

一般来说,这段代码将以“$key”的相同值执行多次。因此,在大多数情况下,$array[$key]将被设置,isset()将返回FALSE。

To clarify for those who fear that I'm treating non-identical code as if it were identical: as far as this part of the program is concerned, $val is a constant. It isn't known until run-time, but it's set earlier in the program and doesn't change here. So both forms produce the same result. And this is the most convenient place to get at $val.

为了澄清那些担心我把不相同的代码当作相同的:对于程序的这一部分来说,$val是一个常量。它直到运行时才知道,但是它在程序中设置得更早,在这里不会改变。所以两种形式产生的结果是一样的。这是最方便的地方在$val。

9 个解决方案

#1


10

For an array you actually want: array_key_exists($key, $array) instead of isset($array[$key]).

对于一个你真正想要的数组:array_key_exists($key, $array)而不是isset($array[$key])。

更多相关文章

  1. PHP / Ajax:如何在成功登录后启动会话(剩余代码工作)
  2. php二维码/26行代码制作php二维码phpqrcode加grafika水印
  3. php分页代码的问题,显示了两个当前页码,求大神解答
  4. PHP开发微信支付代码及支付通知处理
  5. 请问如何用php实现表单提交后以邮件的形式把表单内容发到邮箱中
  6. Symfony2 -从数据库中提取数据并以表单形式显示
  7. 几个有用的php字符串过滤,转换函数代码
  8. 在Web Page中包含PHP代码
  9. 您是否认为PHP中的错误形式是在类方法中访问超级全局变量?

随机推荐

  1. Android获取在桌面上有图标的app列表的方
  2. Android Camera 模块分析
  3. android CallCard.java/updateState(Phon
  4. android 连接webservice
  5. android 通过百度地图定位获取坐标在导航
  6. android:layout_gravity和android:gravit
  7. Android视图框架
  8. 【Android自学笔记】android实现TextView
  9. Android的地图服务
  10. Android获取在线视频的缩略图方式对比