- 公開日
phpの@(アットマーク)はオーバーヘッドが大きいから使わないほうがよい
事の発端はこれ。Arrayにキーがセットされていて、かつ、そのキーの値をチェックしたい。<?php
// 1.
if (isset($checkedAry['key']) && $checkedAry['key'] == "val") {
// 処理
}
// 2. 1より早いんじゃね?
if ($checkedAry['key'] == "val") {
// でもNoticeでちゃうよ!
// PHP Notice: Undefined index: index
}
// 3. 2の「PHP Notice」の回避策 @
if (@$checkedAry['key'] == "val") {
// 処理
}
1と3なら3のほうが処理早いんじゃね?ってことで試してみたところ、こうなった。 (PHP 5.3.3)<?php
$ary = array(
array( "key1" => "val1", "key2" => "val2","key3" => "val3","key4" => "val4"),
array( "key1" => "val1", "key2" => "val2","key3" => "val3"),
);
$time_start = microtime(true);
$index = 0;
foreach (range(1,100000) as $count) {
$index = 1 - $index;
$checkedAry = $ary[$index];
if (isset($checkedAry['key4']) && $checkedAry['key4'] == "val4") {
pow($count, $count);
}
}
$time = microtime(true) - $time_start;
echo "$time second";
$time_start = microtime(true);
$index = 0;
foreach (range(1,100000) as $count) {
$index = 1 - $index;
$checkedAry = $ary[$index];
if (@$checkedAry['key4'] == "val4") {
pow($count, $count);
}
}
$time = microtime(true) - $time_start;
echo "$time second";
3回やってみてこんな結果でした。
0.098845958709717 second
0.19816088676453 second
0.097808122634888 second
0.15862894058228 second
0.10174417495728 second
0.16551208496094 second
つまり@付きのほうがそうじゃないほうより1.5倍~2倍程度遅い、ということになります。
ただ、@付きのほうがシンプルに書ける場合もあるので、今回の例のようにループさせている場合でないのであれば、@付きを使ってもよいのかもしれません。