Page 1 of 1

fastest way to get file

Posted: Wed Mar 19, 2003 7:38 pm
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().

Posted: Wed Mar 19, 2003 9:46 pm
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

Posted: Wed Mar 19, 2003 9:59 pm
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 ;)

Posted: Wed Mar 19, 2003 11:05 pm
by Sevengraff
ok, i guess i'll just use fopen then.
are there other ways to get all the data from a file?

Posted: Wed Mar 19, 2003 11:09 pm
by Stoker
from php version >4.3 you can use file_get_contents() , which is faster I dunno

Posted: Wed Mar 19, 2003 11:24 pm
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

Posted: Thu Mar 20, 2003 2:18 am
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.