免费邮箱 |加入收藏 | 会员中心 | 我要投稿 | RSS
您当前的位置:首页 > PHP专区 > PHP技巧

引用的解释

时间:2011-05-16 15:55:22  来源:站内  作者:潘春会
In addition to the note made by "Francis dot a at gmx dot net" you should not normally be using a function such as sizeof() or count() in a control structure such as FOR because the same value is being calculated repeatedly for each iteration. This can slow things down immensely, regardless of whether you pass by value or reference.

It is generally much better to calculate the static values before the defining the looping control structure.

Example:

<?php

$intSize
= sizeof($arrData);

for(
$i = 0; $i < $intSize; $n++) {
   
// Do stuff
}

?>

Carlos (15-Mar-2005 04:09)

 

 

 

in the example below, you would get the same result if you change the function to something like:

function test_ref(&$arr) {
   $time = time();
   $size = sizeof($arr);       // <--- this makes difference...
   for($n=0; $n<$size; $n++) {
       $x = 1;
   }

   echo "<br />The function using a reference took ".(time() - $time)." s";
}

Francis dot a at gmx dot net (10-Feb-2005 02:53)

 

 

 

I don't know if this is a bug (I'm using PHP 5.01) but you should be careful when using  references on arrays.
I had a for-loop that was incredibly slow and it took me some time to find out that most of the time was wasted with the  function sizeof() at every loop, and even more time I spent  finding out that this problem it must be somehow related to the fact, that I used a reference of the array. Take a look at the following example:

function test_ref(&$arr) {
    $time = time();
    for($n=0; $n<sizeof($arr); $n++) {
        $x = 1;
    }
    echo "<br />The function using a reference took ".(time() - $time)." s";
}

function test_val($arr) {
    $time = time();
    for($n=0; $n<sizeof($arr); $n++) {
        $x = 1;
    }
    echo "<br />The funktion using a value took: ".(time() - $time)." s";
}

// fill array
for($n=0; $n<2000; $n++) {
    $ar[] = "test".$n;
}

test_ref($ar);
test_val($ar);
echo "<br />Done";

When I tested it, the first function was done after 9 seconds, while the second (although the array must be copied) was done in not even one.

The difference is inproportional smaller when the array size is reduced:
When using 1000 loops the first function was running for 1 second, when using 4000 it wasn't even done after 30 Seconds.

jw at jwscripts dot com (16-Oct-2004 08:18)

 

 

 

Re-using variables which where references before, without unsetting them first, leads to unexpected behaviour.

The following code:

<?php

$numbers
= array();

for (
$i = 1; $i < 4; $i++) {
   
$numbers[] =
来顶一下
返回首页
返回首页
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表
推荐资讯
如何找出DHCP地址池里未使用的IP地址
如何找出DHCP地址池里
国内常用的DNS列表
国内常用的DNS列表
Linux邮件服务器软件比较
Linux邮件服务器软件比
学用纯CSS打造可折叠树状菜单
学用纯CSS打造可折叠树
相关文章
栏目更新
栏目热门