~bohwaz/blog/

Avec de vrais morceaux de 2.0 !

PHP bench: require_once versus array_key_exists based require object

This a simple bench to see if require_once is the fastest solution to require a file only one time, versus a custom object using an internal array.

All tests, b.php:

<?php $GLOBALS['a']++; ?>

First test, a.php (require_once):

 <?php
 $a = 1;

 for ($i = 0; $i < 10000; $i++)
 {
   require_once 'b.php';
 }

 echo "$a
";
 ?>

Results:

real	0m3.640s
user	0m0.308s
sys	0m0.740s

Second test, a.php (array based custom require object):

 <?php
 class myRequire
 {
   static private $files = array();

   static public function load($file)
   {
       if (array_key_exists($file, self::$files))
       {
           return true;
       }

       require $file;
       self::$files[$file] = true;
       return true;
   }
 }

 $a = 1;

 for ($i = 0; $i < 10000; $i++)
 {
     myRequire::load('b.php');
 }

 echo "$a
";
 ?>

Results:

real	0m0.080s
user	0m0.064s
sys	0m0.016s

Yeah, require_once seems a bit slow after all, because it will open and do a fstat() on the file each time its called, even if the file has already been included.

Write a comment
(optional)
(optional)
(mandatory)
       _               
__   _(_)___  ___ _ __ 
\ \ / / / __|/ _ \ '__|
 \ V /| \__ \  __/ |   
  \_/ |_|___/\___|_|   
                       
(mandatory)

URLs will create links automatically.
Allowed HTML tags: <blockquote> <cite> <pre> <code> <var> <strong> <em> <del> <ins> <kbd> <samp> <abbr>