简体   繁体   中英

How to make array loop faster in PHP

Is there a way to make this faster?

while ($item = current($data))
{
    echo '<ATTR>',$item, '</ATTR>', "\n";
    next($data);
}

I do not like that I need to create new variables like $item.

<?php
$transport = array('foot', 'bike', 'car', 'plane');

foreach ($transport as $value) {
    echo $value;
}
?>

If you don't want to create temporary variables, do it like this:

while (current($data))
{
    echo '<ATTR>',current($data), '</ATTR>', "\n";
    next($data);
}

However, I don't know if this will really make it any faster. They only way to tell would be with a profiler, but it is such a micro-optimization I doubt you will notice the difference.

The best way to speed up the loop would be to use a faster computer.

If all you're doing is the code above you could use an implode statement.


if (count($data) > 0) {
     echo "<ATTR>".implode("</ATTR>\n<ATTR>", $data)."</ATTR>";
}

$nl = "\\n";

while ($item = current($data))
{
    echo '<ATTR>',$item, '</ATTR>',$nl;
    next($data);
}

Store the newline character into a variable rather then having PHP parse the double quotation marks in every iteration.

You could do a foreach, but then you would be creating 2 new variables. Unless you just don't like the idea of assigning variables inside the while() clause.

foreach($data as $key => $value)
{
    echo $key . " => ".$value;
}

Either way, you are going to need to create an actual variable.

What about this one :

function my_func($str) {
    echo "<attr>{$str}</attr>\n";
}
array_map('my_func', $data);

(Should work, but I'm curious about it's speed compared with a foreach loop)

Or, if you are using PHP >= 5.3 (probably not your case, btw) , you can use this one, based on a lambda function :

array_map(function ($item) {
    echo "<attr>{$item}</attr>\n";
}, $data);

Almost the same, but without having to declare a function used only once in the program.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM