10
9

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.

「===」は本当に速いのか?

10
Posted at

一般に「===」は型変換をしない分「==」より速いと言われているが、
本当に速いんかテストしてみた。

  • 条件

for-loopで10,000,000回テスト
if文で比較
num = 1000 : 数値
str = "1000" :文字列

  • 結果
比較 処理時間[sec]
str == str 1.9021899700165
str === str 0.62406301498413
num == num 0.64606380462646
num === num 0.65006494522095
str == num 1.3471341133118
str === num 0.68006801605225

文字列同士の比較であれば「===」の方が速い。
数値同士の比較であれば「==」の方がちょっと速い。(意外!)
文字列数値の比較であれば「===」の方が速い。

基本「===」で比較で問題ないみたい。

環境によっては違う結果になる可能性も・・・。

<?php

// 試行回数
const MAX = 10000000;


$num = 1000;
$str = "1000";


//
$begin = microtime(true);
for ($i=0; $i<MAX; $i++){
  if ($str=="10000"){
    ;
  }
}
$finish = microtime(true);

echo "str == str ".($finish - $begin)."[sec]\n";


//
$begin = microtime(true);
for ($i=0; $i<MAX; $i++){
  if ($str==="10000"){
    ;
  }
}
$finish = microtime(true);

echo "str === str ".($finish - $begin)."[sec]\n";


//
$begin = microtime(true);
for ($i=0; $i<MAX; $i++){
  if ($num==10000){
    ;
  }
}
$finish = microtime(true);

echo "num == num ".($finish - $begin)."[sec]\n";


//
$begin = microtime(true);
for ($i=0; $i<MAX; $i++){
  if ($num===10000){
    ;
  }
}
$finish = microtime(true);

echo "num === num ".($finish - $begin)."[sec]\n";


//
$begin = microtime(true);
for ($i=0; $i<MAX; $i++){
  if ($str==$num){
    ;
  }
}
$finish = microtime(true);

echo "str == num ".($finish - $begin)."[sec]\n";


//
$begin = microtime(true);
for ($i=0; $i<MAX; $i++){
  if ($str===$num){
    ;
  }
}
$finish = microtime(true);

echo "str === num ".($finish - $begin)."[sec]\n";
10
9
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
10
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?