Copy from stream - comparing different ways

    There was a task from php: // input to copy the data to the desired file.
    I decided to check for speed the possible ways to copy a file of 9 megabytes in size from php: // stdin.
    There are several of them:
    • Reading in blocks via fread () and writing through fwrite ()
    • Record content using file_put_contents () data retrieved using file_get_contents ()
    • Copying using the copy () file copy function
    • Using stream_copy_to_stream (). appeared in PHP5
    Results fread / fwrite:
    Memory used up: 9440 bytes.
    Spent time: 0.09 seconds.

    Results file_get_contents / file_put_contents:
    Memory used up: 940 bytes.
    Time spent: 0.06 sec;

    Results copy ():
    Memory used up: 1008 bytes.
    Time spent: 0.05 sec;

    Results stream_copy_to_stream:
    Memory used up: 1240 bytes.
    Time spent: 0.04 sec;

    What is most interesting, stream_copy_to_stream turned out to be faster than copy (). If you take a regular file, NOT a stream, then the results will most likely be in favor of copy ()

    UPD: phpclub.ru/paste/index.php?show=1993 - UPD 2 test code

    :Tested on a file in 240Mb. Everything but the fread / fwrite wins (about 30 seconds versus 60).
    So on large files it is not recommended to use it and file_get_contents due to the fact that the corresponding memory_limit values ​​are needed in php.ini.

    As a result, I did it on stream_copy_to_stream.

    Also popular now: