LoginSignup
2
0

More than 3 years have passed since last update.

【PHP】foreach, array_map, array_walkの処理速度比較 forとwhileのおまけあり

Last updated at Posted at 2019-09-06

はじめに

夜ふとarray_mapのことを考えていたら、眠れなくなったのでサクッと試した結果

PCスペック

  • macOS Mojave
  • 2.3 GHz Intel Core i5
  • メモリ16GB

方法

  • loop.phpとmap.phpとwalk.phpを用意
  • 0から999999の100万の配列を用意し、累乗したものを入れ直す
  • 10回ずつ実行し、平均を出す
$ php loop.php

のような形で実行し、処理速度を出す

ソースコード

loop.php
<?php

$start = microtime(true);

foreach ($arr = range(0, 999999) as $key => $value) {
    $arr[$key] = $value**2;
}

$end = microtime(true) - $start;
echo "{$end} 秒";

map.php
<?php

$start = microtime(true);

$arr = array_map(function($i){ return $i**2;}, range(0,999999));

$end = microtime(true) - $start;
echo "{$end} 秒";
walk.php
<?php

$start = microtime(true);

array_walk($arr = range(0, 999999), function(&$i){ return $i**2;});

$end = microtime(true) - $start;
echo "{$end} 秒";

結果

loop map walk
1 0.06867098808 0.07462501526 0.1094799042
2 0.06750392914 0.07323098183 0.1181879044
3 0.06451797485 0.07551503181 0.1073791981
4 0.06446099281 0.08033800125 0.1189579964
5 0.06456112862 0.0758960247 0.1152040958
6 0.06685209274 0.07563400269 0.106719017
7 0.07046103477 0.07318592072 0.1079549789
8 0.06416606903 0.07384204865 0.1147558689
9 0.06298303604 0.07454109192 0.1074810028
10 0.0647149086 0.07654190063 0.1151940823
average 0.06588921547 0.07533500195 0.1121314049

所感

foreachが一番早いのか...という感想
個人的には、array_mapとかarray_mapの方が好きなんだけど、array_walkとforeachの差がすごい。
単純な処理だと対して変わらなそうだが、中でごにょごにょしたりするとキツそう。
個人的にはぱっと見の可読性はforeachはいいが、スマートな関数達の方が好みだから状況によって使い分けます。

おまけ

for.php
<?php

$start = microtime(true);

for ($i=0; $i < 1000000; $i++) { 
    $arr[] = $i ** 2;
}

$end = microtime(true) - $start;
echo "{$end} 秒";

だいたい0.042~0.043秒くらい。

while.php
<?php

$start = microtime(true);

$i = 0;
while ($i < 1000000) {
    $arr[] = $i ** 2;
    $i++;
}

$end = microtime(true) - $start;
echo "{$end} 秒";

だいたい0.041~0.042秒くらい。

配列操作ではないので、実プロダクトでの応用は効かないが、この処理だとforとwhileがほぼ同じくらいで一番早かった。

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0