LoginSignup
7
6

More than 5 years have passed since last update.

foreachよりlist,eachのほうがメモリを消費しないというお話を検証してみた

Posted at

ちゃんと検証しなさいと突っ込まれてしまったので検証してみました。

検証コードは以下の二つ

test1.php
<?php
$data = [];
for($i = 0; $i < 800000; $i++) {
  $data[] = "あ";
}
echo "point1:".memory_get_usage()."\n";
foreach ($data as $d) {}
echo "point2:".memory_get_usage()."\n";
test2.php
<?php
$data = [];
for($i = 0; $i < 800000; $i++) {
  $data[] = "あ";
}
echo "point1:".memory_get_usage()."\n";
while(list($key, $value) = each($data)) {}
echo "point2:".memory_get_usage()."\n";

これでちゃんと検証できるのか自信はないんですが、まあこんなコードにしてみました。
環境はMBAでphpbrewな環境でphp-5.4.26で実行させてます。
ちなみにphp-5.5.10でも実行させましたが、結果はほとんど変わらないです。

foreachを使ったループ、test1.phpの実行結果

回数 point1(kb) point2(kb) time(s)
1 114664.87 114664.98 0.14
2 114664.87 114664.98 0.14
3 114664.87 114664.98 0.13
4 114664.87 114664.98 0.14
5 114664.87 114664.98 0.13

list,eachを使ったループ、test2.phpの実行結果

回数 point1(kb) point2(kb) time(s)
1 114665.06 114665.27 0.32
2 114665.06 114665.27 0.32
3 114665.06 114665.27 0.33
4 114665.06 114665.27 0.36
5 114665.06 114665.27 0.34

結果から見えてくる事

foreach使ってた方が全然よいですね。メモリ使用量はそんなにかわらないし、速度はlist,eachのほうが遅いし・・・
まあ今の時代list,eachなんて使う人はいないか。

7
6
1

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
7
6