Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

readdir vs scandir

Tags:

php

1] Which of the functions is faster?
2] what are the differences?

Differences

1] readdir returns the name of the next entry in the directory. Scandir returns an array of files and directories from the directory.

2] readdir has to have a resource handle open until all the entries are read. scandir, perhaps creates an array of all the entries and closes the resouce handle?

like image 384
ThinkingMonkey Avatar asked Jan 01 '12 10:01

ThinkingMonkey


People also ask

What is Scandir?

The scandir() function returns an array of files and directories of the specified directory.

What is the functionality of Readdir?

The readdir() function returns a pointer to a structure representing the directory entry at the current position in the directory stream specified by the argument dirp, and positions the directory stream at the next entry. It returns a null pointer upon reaching the end of the directory stream.


2 Answers

Just getting the results (without doing anything), readdir is a minimum faster:

<?php  $count = 10000;  $dir = '/home/brati';  $startScan = microtime(true); for ($i=0;$i<$count;$i++) {     $array = scandir($dir); } $endScan = microtime(true);   $startRead = microtime(true); for ($i=0;$i<$count;$i++) {     $handle = opendir($dir);     while (false !== ($entry = readdir($handle))) {         // We do not know what to do     } } $endRead = microtime(true);  echo "scandir: " . ($endScan-$startScan) . "\n"; echo "readdir: " . ($endRead-$startRead) . "\n"; 

Gives:

== RUN 1 == scandir: 5.3707950115204 readdir: 5.006147146225  == RUN 2 == scandir: 5.4619920253754 readdir: 4.9940950870514  == RUN 3 == scandir: 5.5265231132507 readdir: 5.1714680194855 

Then of course it depends on what you intend to do. If you have to write another loop with scandir(), it will be slower.

like image 56
aufziehvogel Avatar answered Oct 02 '22 02:10

aufziehvogel


It really depends what you're doing with the data.

If you're going through entry-by-entry, you should be using readdir, if you actually need to have a list of the entries in memory, you should be using scandir.

There's no sense copying information into memory when you're going to be using it entry-by-entry anyway. Lazy evaluation is definitely the way to go in that case.

I would imagine that scandir is just a wrapper around the same thing that readdir is calling, and would therefore be slower.

like image 43
Robert Allan Hennigan Leahy Avatar answered Oct 02 '22 03:10

Robert Allan Hennigan Leahy