- var_dump: documentation ( source)
- microtime: documentation ( source)
- pow: documentation ( source)
- sprintf: documentation ( source)
- md5: documentation ( source)
<?php
$a = array();
for($i = 0; $i < pow(10, 5); $i++) {
$a[$i] = array(
md5($i.microtime(true))
);
}
$sum = 0;
$times['for']['before'] = microtime(true);
for($j = 0; $i < count($a); $i++) {
$sum += 1000;
}
$times['for']['after'] = microtime(true);
unset($sum);
$sum = 0;
$times['foreach']['before'] = microtime(true);
foreach($a as $k) {
$sum += 1000;
}
$times['foreach']['after'] = microtime(true);
unset($sum);
$t_for = $times['for']['after'] - $times['for']['before'];
$t_foreach = $times['foreach']['after'] - $times['foreach']['before'];
var_dump(array(
'for' => sprintf('%f', $t_for),
'foreach' => sprintf('%f', $t_foreach),
'is for faster than foreach?' => $t_for < $t_foreach,
'how much faster?' => (1 - ($t_for / $t_foreach)))
);