php 配列に値挿入時の「array_push」と「[] =」のパフォーマンスの計測する

php 配列に値挿入時の「array_push」と「[] =」のパフォーマンスの計測する

phpで、配列に値挿入時の「array_push」と「[] =」のパフォーマンスの計測するサンプルコードを記述してます。phpのバージョンは8.0です。

環境

  • OS  CentOS Linux release 8.0.1905 (Core)
  • php 8.0.0
  • nginx 1.14.1

実行時間計測

microtimeを使用すれば、処理にかかった時間を計測することが可能です。

$startTime = microtime(true);

// 処理を記述

$time = microtime(true) - $startTime; // 処理にかかった時間(ミリ秒)

以下は、配列に値挿入時の「array_push」と「[] =」のパフォーマンスの計測するサンプルコードとなります。

<?php

// 100万回実行
define('COUNT', 1000000); 

$arr = [];

// 計測開始
$startTime = microtime(true);

for ($i = 0; $i < COUNT; ++$i)
{    
    array_push($arr, $i);
}

result($startTime,'array_push');


$arr = [];

// 計測開始
$startTime = microtime(true);

for ($i = 0; $i < COUNT; ++$i)
{
    $arr[] = $i;
}

result($startTime,'[] =');

function result($time,$str){
    
    echo '測定結果 : ' . $str . PHP_EOL;
    // 表示は少数第5桁まで
    echo "process time: " . number_format((microtime(true) - $time),5) . ' ミリ秒' . PHP_EOL;    
    echo PHP_EOL;
}

測定結果

[1回目] 
測定結果 : array_push
process time: 0.30982 ミリ秒

測定結果 : [] =
process time: 0.08672 ミリ秒

[2回目] 
測定結果 : array_push
process time: 0.30045 ミリ秒

測定結果 : [] =
process time: 0.08627 ミリ秒

[3回目] 
測定結果 : array_push
process time: 0.31760 ミリ秒

測定結果 : [] =
process time: 0.08611 ミリ秒

[] =の方が、かなりパフォーマンスが良いという結果となりました。