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

More than 5 years have passed since last update.

PHPのdatetime文字列の比較にstrtotime()を噛ませるとどれくらい遅くなるか確認してみた

Last updated at Posted at 2019-07-20

前提として

phpでdatetimeの文字列を扱う上では色々な課題や注意点があります
参考:【PHP入門】日付を取得・比較する方法と注意点まとめ

ここでは純粋に実行速度の確認だけを実施して、良し悪しについては触れません。

やってみた

PHP7.2です。

全貌

Github - compare-processing-speed-casted-datetime

プロジェクト名は英語ガバなので許してください
以下にコード記述しているので、みなくて大丈夫です

文字列そのままの比較をするコード

10万回比較を10セット実施し、実行時間を得る

<?php
    $datetime_today  = date('Y-m-d H:i:s');
    $datetime_future = '2020-07-24 00:00:00';

    echo '文字列そのままの比較' . PHP_EOL;
    for ($count=0; $count<10; $count++) {
        $time_start = microtime(true);

        // 10万回の判定する
        for ($i=0; $i < 100000; $i++) {
            if ($datetime_today > $datetime_future) {
                // do nothing
            }
        }

        $time = microtime(true) - $time_start;
        echo $time . ' 秒' . PHP_EOL;
    }

文字列をstrtotime変換してからの比較をするコード

同じく10万回比較を10セット実施し、実行時間を得る

<?php
    $datetime_today  = date('Y-m-d H:i:s');
    $datetime_future = '2020-07-24 00:00:00';

    echo '文字列そのままの比較' . PHP_EOL;
    for ($count=0; $count<10; $count++) {
        $time_start = microtime(true);

        // 10万回の判定する
        for ($i=0; $i < 100000; $i++) {
            if (strtotime($datetime_today) > strtotime($datetime_future)) {
                // do nothing
            }
        }

        $time = microtime(true) - $time_start;
        echo $time . ' 秒' . PHP_EOL;
    }

実行結果

文字列そのままの比較
0.0070090293884277 秒
0.0046958923339844 秒
0.0039851665496826 秒
0.004115104675293 秒
0.004082202911377 秒
0.0045111179351807 秒
0.0044329166412354 秒
0.0046958923339844 秒
0.0042669773101807 秒
0.0043740272521973 秒

文字列をstrtotime変換してからの比較
0.23847007751465 秒
0.23226594924927 秒
0.23400783538818 秒
0.23232102394104 秒
0.23448014259338 秒
0.23279094696045 秒
0.23338794708252 秒
0.23172903060913 秒
0.23631811141968 秒
0.23155283927917 秒

結論

strtotime()使わない方が50倍くらい早い!!
結構顕著な数字が出る。

2
1
0

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