logo
Published on Code2Design (http://code2design.com)

glob vs opendir

By David
Created Nov 25 2007 - 5:17am

After much testing I find that although glob() is much cleaner than opendir(), it is also much slower.

I started by making a dir called "cache" in which I placed a single 65k html file filled with whitespace (just so I could have a large filesize without worrying about char output).

Based on the code below:

<?php

//Waste a little time to offset PHP's startup.
for($i=0$i<20$i++) { 
    print 
' '
}




$start_time time()+microtime(true);

ob_start();
for(
$x=0$x 20$x++) {
   
$dir 'cache/';
    if (
is_dir($dir)) {
        if (
$dh opendir($dir)) {
            while ((
$file readdir($dh)) !== false) {
               
//Include the file 
               
include($file);
               
//$value = rand(0, 10000) * 2345678;
           
}
           
closedir($dh);
        }
    }
}
ob_end_clean();

print ((
time()+microtime(true)) - $start_time). ' (opendir time)<br />';





$start_time time()+microtime(true);

ob_start();
for(
$x=0$x 20$x++) {
   
//Include the function files
   
foreach (glob("cache/*.html") as $file) {
       
//Include the file 
       
include($file);
       
//$value = rand(0, 10000) * 2345678;
   
}
}
ob_end_clean();

print ((
time()+microtime(true)) - $start_time). ' (glob time)<br />';
?>

The result was:
0.0069890022277832 (opendir time)
0.027945041656494 (glob time)

So I can honestly recommend opendir if you plan on including the files in the dir.

‹ PHP Newbie - Printing what I write? [0] Help with sockets in php › [0]

Source URL:
http://code2design.com/forums/glob_vs_opendir