Qiita Conference 2025

みのるん (@minorun365)

30代からでも遅くない! 内製開発の世界に飛び込み、最前線で戦うLLMアプリ開発エンジニアになろう

0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

array_mergeはpushするよりも30倍遅い

Posted at
$ php test.php 
Xdebug: [Step Debug] Could not connect to debugging client. Tried: localhost:9003 (through xdebug.client_host/xdebug.client_port).
=== array_merge を使用する場合 ===
array_merge の実行時間: 18.542617082596 秒

=== foreach と array_push を使用する場合 ===
foreach + array_push の実行時間: 0.53139305114746 秒
bool(true)
test.php
<?php
ini_set('memory_limit', '2048M');

$baseArray = range(1, 10000);

echo "=== array_merge を使用する場合 ===\n";

$resultMerge = [];  // 初期は空の配列
$startMerge = microtime(true);
for ($i = 0; $i < 1000; $i++) {
    // 毎回、新しい配列として再代入する
    $resultMerge = array_merge($resultMerge, $baseArray);
}
$timeMerge = microtime(true) - $startMerge;
echo "array_merge の実行時間: {$timeMerge}\n";

echo "\n=== foreach と array_push を使用する場合 ===\n";

$resultPush = [];  // 初期は空の配列
$startPush = microtime(true);
for ($i = 0; $i < 1000; $i++) {
    foreach ($baseArray as $value) {
        $resultPush[] = $value;
    }
}
$timePush = microtime(true) - $startPush;
echo "foreach + array_push の実行時間: {$timePush}\n";

var_dump(json_encode($resultMerge) === json_encode($resultPush));

0
1
2

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

@7mpy

PHPerのPHPerによるPHPerのためのLaravel

Comments

nmcr5575
@nmcr5575
echo "\n=== foreach と array_push を使用する場合 ===\n";

$resultPush = [];  // 初期は空の配列
$startPush = microtime(true);
for ($i = 0; $i < 1000; $i++) {
   foreach ($baseArray as $value) {
       $resultPush[] = $value;
   }
}
$timePush = microtime(true) - $startPush;
echo "foreach + array_push の実行時間: {$timePush}\n";

array_pushの実行時間の検証なら、$array[] = ではなく array_push()関数を使うべきでは?

注意: もし配列にひとつの要素を加えるために array_push() を使用するなら、 関数を呼ぶオーバーヘッドがないので、$array[] = を使用するほうがいいです。

とあるように、オフィシャルでも別物扱いです。

1
ibyrjbf
@ibyrjbf

array_mergeはpushするよりも30倍遅い

そもそも、用途や出来ることが異なるので、速度を比較すること自体ナンセンスかと。

1

Let's comment your feelings that are more than good

Qiita Conference 2025 will be held!: 4/23(wed) - 4/25(Fri)

Qiita Conference is the largest tech conference in Qiita!

Keynote Speaker

ymrl、Masanobu Naruse, Takeshi Kano, Junichi Ito, uhyo, Hiroshi Tokumaru, MinoDriven, Minorun, Hiroyuki Sakuraba, tenntenn, drken, konifar

View event details

Being held Article posting campaign

0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Login to continue?

Login or Sign up with social account

Login or Sign up with your email address