phpのevalとincludeの速度

http://blog.xole.net/article.php?id=288

phpで動的クラス生成見て。一度ディスクに書き出してそれ読み込んでなんて冗長過ぎる処理するとevalがいくら遅いつってもDisk I/O処理のほうがだいぶ時間かかるんじゃないかと。

なんでベンチマークとってないのか疑問なんだけど、つーことで簡単なプログラム書いてベンチマーク。環境はLinuxApache 2.0.53 + PHP 5.0.4。

まずはinclude版。

<?php
require_once "Benchmark/Timer.php";
$timer = new Benchmark_Timer;
$timer->start();

$source = file_get_contents('./foo.php',false);
$source = str_replace('__SKELTON_CLASS','Foo',$source);
$file = '/tmp/foo.class.php';
$fp = fopen( $file, "w" );
fwrite( $fp, $source );
include_once( $file );
unlink( $file );
new Foo('Foo');

$timer->stop();
echo "<pre>";
print_r($timer->getOutput());
echo "</pre>";
?>

#foo.php
<?php
class __SKELTON_CLASS{
  function __construct($string){
    echo $string,"\n";
  }
}?>

実行結果

Foo 
  time index ex time %
  Start 1124423291.98966100 - 0.00%
  Stop 1124423291.99113000 0.001469 100.00%
  total - 0.001469 100.00% 

次にeval版

<?php
require_once "Benchmark/Timer.php";
$timer = new Benchmark_Timer;
$timer->start();

$source = file_get_contents('./foo_eval.php',false);
$source = str_replace('__SKELTON_CLASS','Foo',$source);
eval($source);
new Foo('Foo');

$timer->stop();
echo "<pre>";
print_r($timer->getOutput());
echo "</pre>";
?>
# foo_eval.php
class __SKELTON_CLASS{
  function __construct($string){
    echo $string,"\n";
  }
}

実行結果

Foo 
  time index ex time %
  Start 1124423026.60654400 - 0.00%
  Stop 1124423026.60732700 0.000783 100.00%
  total - 0.000783 100.00% %

最後にtmpfs使ったinclude版。最初のiclude版の$fileを$file = '/dev/shm/foo.class.php';としただけ。

実行結果

Foo 
  time index ex time % 
  Start 1124423551.65305700 - 0.00% 
  Stop 1124423551.65414700 0.001090 100.00% 
  total - 0.001090 100.00% 

三つの実行速度を並べると

  • include版
    • 1.469ms
  • eval版
    • 0.783
  • tmpfs使ったinclude版
    • 1.090

とevalを使ったのが一番速い結果に。

まったく関係ないけどはてな記法ソースコード記述しにくい。