douyin9987 2013-10-11 21:05
浏览 10
已采纳

PHP Microbenchmarking(变量与条件语句)

This question might be "a bit out there". But more or less it's microbenching code, but it's to improve my standards and general knowledge of PHP's backend.

SO! Here I go, my question! Would calling a variable twice require less memory (and load on CPU) than calling an additional else condition in PHP? Which requires more resources? And why?

The Below examples:
A, shows calling a variable twice and B, shows calling an additional else condition. Both have the same end result, of course.

Any additional references to any answers (responds) would be highly appropriated too! If possible.

Example A:

$a = 1;
if (isset($array['a']))
{
    $a = $array['a'];
}

$b = NULL;
if (isset($array['b']))
{
    $b = $array['b'];
}



Example B:

if (isset($array['a']))
{
    $a = $array['a'];
}
else
{
    $a = 1;
}

if (isset($array['b']))
{
    $b = $array['b'];
}
else
{
    $b = NULL;
}
  • 写回答

4条回答 默认 最新

  • dpleylxzx47207117 2013-10-11 22:31
    关注

    I created a mini benchmark, to see which is faster. The following evaluates both functions exactly 100 times. Inside of the two functions, they evaluate your examples exactly 100,000 times. On my home Ubuntu web server, the output is similar to this.

    6.0754749774933 = Giving the variable a default value.

    4.8433840274811 = Using an else statement instead.

    The second example (else statements) is two seconds faster, however the example is being executed 10,000,000 (10 million) times. In a real-life example, the readability of the code and what your team prefers is more important than saving a few milliseconds.

    To answer your question, there is almost 0 difference when using either method.

    If you want my opinion, I prefer the second example.

    Here is the benchmarking code I used. http://phpfiddle.org/api/raw/8nm-d72

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 Macbookpro 连接热点正常上网,连接不了Wi-Fi。
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题