It seems foreach() operates much faster than equivalent while() loop.
This is result is not what I expect. Foreach() operates on copy of array and I
thought it would work a little slower than while().
Anyone has a good explanation why foreach is faster? i.e. What kind of overhead
cause this?
I'm using PHP4.0.4pl1 as Apache DSO on Linux.
and curious about this result.
Thanks.
======= output =========
Array
(
[0] => Array
(
[name] => Start
[time] => 984534909.65571400
[diff] => -
[total] => 0
)
[1] => Array
(
[name] => Marker: FOREACH
[time] => 984534913.41161600
[diff] => 3.755902
[total] => 3.755902
)
[2] => Array
(
[name] => Marker: WHILE
[time] => 984534919.34682700
[diff] => 5.935211
[total] => 9.691113
)
[3] => Array
(
[name] => Stop
[time] => 984534919.34700000
[diff] => 0.000173
[total] => 9.691286
)
)
========= end ================
========= code ==========
<html>
<head>
<title>Foreach & While Bench</title>
</head>
<body bgcolor="#FFFFFF">
<pre>
<?php
require_once('classlib/Benchmark/Timer.php'); // PEAR Timer.php
$timer = new Benchmark_Timer;
$timer->start();
for ($i = 0; $i < 10000; $i++) {
foreach($HTTP_SERVER_VARS as $k => $v) {
$key = $k;
$val = $v;
}
}
$timer->set_marker("Marker: FOREACH");
for ($i = 0; $i < 10000; $i++) {
reset($HTTP_SERVER_VARS);
while(list($k,$v) = each($HTTP_SERVER_VARS)) {
$key = $k;
$val = $v;
}
}
$timer->set_marker("Marker: WHILE");
$timer->stop();
$profiling = $timer->get_profiling();
print_r($profiling);
?>
</pre>
</body>
</html>
======== code ==========
Yasuo Ohgaki
=========================
My favorite links
[RFC] http://www.faqs.org/rfcs/ [W3C] http://www.w3.org/
[PHP Manual] http://www.php.net/manual/en/
--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
To contact the list administrators, e-mail: [EMAIL PROTECTED]
- Re: [PHP] foreach() faster than while()? Yasuo Ohgaki
- Re: [PHP] foreach() faster than while()? Yasuo Ohgaki
- Re: [PHP] foreach() faster than while()? Dennis Gearon
- Re: [PHP] foreach() faster than while()? Rick St Jean