php 文字列に変換する「strval」と「(string)」と「ダブルクォーテーション」のパフォーマンスを計測する

php 文字列に変換する「strval」と「(string)」と「ダブルクォーテーション」のパフォーマンスを計測する

phpで、文字列に変換する「strval」と「(string)」と「ダブルクォーテーション」のパフォーマンスを計測するサンプルコードを記述してます。phpのバージョンは8.0です。

環境

  • OS  CentOS Stream release 8
  • php 8.0.0
  • nginx 1.14.1

実行時間計測

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

$startTime = microtime(true);

// 処理を記述

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

以下は、「strval」と「(string)」と「ダブルクォーテーション」を使用して、文字列に変換するコードを1000万回実行して、パフォーマンスを計測するサンプルコードとなります。

<?php

// 1000万回実行
define('COUNT', 10000000);

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

// 文字列に変換する変数

$num1 = 10.11;
$num2 = 10.11;
$num3 = 10.11;

for ($i = 0; $i < COUNT; ++$i) {
    $result1 = strval($num1);
}

result($startTime, 'strval');

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

for ($i = 0; $i < COUNT; ++$i) {
    $result2 = (string)$num2;
}

result($startTime, '(string)');

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

for ($i = 0; $i < COUNT; ++$i) {
    $result3 = "$num3";
}

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回目] 
測定結果 : strval
process time: 2.97431 ミリ秒

測定結果 : (string)
process time: 2.97743 ミリ秒

測定結果 : ""
process time: 2.97763 ミリ秒

[2回目] 
測定結果 : strval
process time: 3.02088 ミリ秒

測定結果 : (string)
process time: 3.02415 ミリ秒

測定結果 : ""
process time: 3.02444 ミリ秒

[3回目] 
測定結果 : strval
process time: 2.98853 ミリ秒

測定結果 : (string)
process time: 2.99737 ミリ秒

測定結果 : ""
process time: 3.00228 ミリ秒

どれもパフォーマンスは、ほぼ同じです。