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.
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.
I do a little bench to comprobe it.
<?php
$a = array();
for ($i = 0; $i < 100000; $i++) {
$a[] = $i;
}
$start = microtime(true);
foreach ($a as $k => $v) {
$a[$k] = $a[$k] + 1;
}
echo "foreach : ", microtime(true) - $start, " Seconds\n";
$start = microtime(true);
foreach ($a as $k => &$v) {
$v = $v + 1;
}
echo "foreach with cursor : ", microtime(true) - $start, " Seconds\n";
$start = microtime(true);
for ($i = 0; $i < count($a); ++$i) {
$a[$i] = $a[$i] + 1;
}
echo "for : ", microtime(true) - $start, " Seconds\n";
$start = microtime(true);
for ($i=0,$l=count($a);$i<$l;++$i) {
$a[$i] = $a[$i] + 1;
}
echo "for with cached count : ", microtime(true) - $start, " Seconds\n";
With results
foreach : 0.0039410591125488 Seconds
foreach with cursor : 0.00357985496521 Seconds
for : 0.0022602081298828 Seconds
for with cached count : 0.0020480155944824 Seconds
Hope this helps
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.