過負荷に耐えるWEBサービス作成のための使えるPHPキャッシュテクニックまとめの記事の一つ目の方法を簡単にテストしてみた。
処理時間を出すコードも追加してちょっと改変したのが以下
<?php
$time_start = microtime(true);
echo hoge(1);
echo "<br>";
echo hoge(2);
echo "<br>";
for($i=0;$i<10000;$i++){
echo hoge(1);
echo "<br>";
}
function hoge($id) {
static $cache;
if (isset($cache[$id])) {
echo "cached!!n";
return $cache[$id];
}
$ret = $id;
for ($i=0;$i<1000;$i++) {
$ret += $i;
}
$cache[$id] = $ret;
return $ret;
}
$time_end = microtime(true);
$time = $time_end - $time_start;
echo "$time";
?>
で、上のプログラムと対戦するのが以下のプログラム
<?php
$time_start = microtime(true);
echo hoge(1);
echo "<br>";
echo hoge(2);
echo "<br>";
for($i=0;$i<10000;$i++){
echo hoge(1);
echo "<br>";
}
function hoge($id) {
$ret = $id;
for ($i=0;$i<1000;$i++) {
$ret += $i;
}
$cache[$id] = $ret;
return $ret;
}
$time_end = microtime(true);
$time = $time_end - $time_start;
echo "$time";
?>
上と下の違いはisset関数でスタティックな変数に値がキャッシュ上に残っていれば、その値を返すか返さないか。
モチのロンロン上の方が早いのだがどれだけ早いのか?
結果は
キャッシュ使う側(上のプログラム):0.015379190444946
キャッシュ使わない側(下のプログラム):0.83459520339966
言わずもがなダンチな結果になりました。
こんなテクニックもあるのだなということを覚えておこう。