fastest way to get file

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Sevengraff
Forum Contributor
Posts: 232
Joined: Thu Apr 25, 2002 9:34 pm
Location: California USA
Contact:

fastest way to get file

Post by Sevengraff »

i was wonder what is faster. i know of two ways to get all the data from a file.

Code: Select all

$file = file($file_location);
$file = implode("", $file);
or

Code: Select all

$fp = fopen($file_location, "rb");
$file = fread($fp, filesize($file_location));
fclose($fp);
I like to use the file()/implode(), because i always forget the arguements when using fopen().
User avatar
daven
Forum Contributor
Posts: 332
Joined: Tue Dec 17, 2002 1:29 pm
Location: Gaithersburg, MD
Contact:

Post by daven »

I am not sure which is faster, although the speed difference is minimal. fopen/fread is binary safe, while file() is not. I tend to use file() for things like reading lines from text files, and fopen() for everything else
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

$file = file($file_location);
$file = implode("", $file);
somehow the file must be read anyway and that's very similar to fread. Then the content is splitted into single lines (searching for linebreaks, creating a new string, add it to an array). Afterwards all elements are concatenated to one string (reallocate storage, append element content).
Yes, I would say fread() is faster ;)
User avatar
Sevengraff
Forum Contributor
Posts: 232
Joined: Thu Apr 25, 2002 9:34 pm
Location: California USA
Contact:

Post by Sevengraff »

ok, i guess i'll just use fopen then.
are there other ways to get all the data from a file?
User avatar
Stoker
Forum Regular
Posts: 782
Joined: Thu Jan 23, 2003 9:45 pm
Location: SWNY
Contact:

Post by Stoker »

from php version >4.3 you can use file_get_contents() , which is faster I dunno
User avatar
Sevengraff
Forum Contributor
Posts: 232
Joined: Thu Apr 25, 2002 9:34 pm
Location: California USA
Contact:

Post by Sevengraff »

Stoker wrote:from php version >4.3 you can use file_get_contents() , which is faster I dunno
thats a pretty cool function, but i dont have 4.3
McGruff
DevNet Master
Posts: 2893
Joined: Thu Jan 30, 2003 8:26 pm
Location: Glasgow, Scotland

Post by McGruff »

This is handy for timing scripts:

Code: Select all

function getmicrotime(){
    list($usec, $sec) = explode(" ",microtime());
    return ((float)$usec + (float)$sec);
}

$start = getmicrotime();

..code to test...

$end = getmicrotime();
$time = $end - $start;
echo $time;
The Mysql Control Centre (mysql.com) also lets you time queries.
Post Reply