I did a test and was really bummed to find that a standard foreach loop performed significantly faster than using array methods.

Using foreach:

$std_dev = 0;
$mean = self::calc_stat_mean($array);

$start = microtime(true);

foreach ($array as $value)
{

    $std_dev += pow(($value - $mean), 2);

}

echo microtime(true) - $start;

Using array methods:

$mean = self::calc_stat_mean($array);

$start = microtime(true);

$std_dev = array_sum(array_map(function($value) use ($mean) {

    return pow(($value - $mean), 2);

}, $array));

echo microtime(true) - $start;

Can someone tell me why this is? I feel the latter method just seems better written and cleaner than the former but the hit in speed isn't worth it.

有帮助吗?

解决方案

The difference is so small that it isn't even worth worrying about.

Just pick something that matches your programming style, that you like better personally, and that will work better for your app.

Find other places to optimize... Don't stress over for, for each, and while!

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top