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