Here's a demonstration concerning the speed of unpacking files:
So let's see which method is fastest between FREAD or SUBSTR?
I was creating a script that could read scenario files from a game, and render a preview of its terrain. The terrain structure within each file was huge (between 100,000 - 1,000,000 blocks containing 3 bits of data each). Therefore, I spent much effort to ensure it was fast and robust.
Method 1: This method retrieves the 3 bits of data found in each block. It uses the loop of widthxheight and implode+unpack+substr each block:
<?php
for ( $Y = 0 ; $Y < ( $width * $height ) ; $Y ++ ) {
$Output [ Map ] [ $Y ] [ TerrainID ] = implode ( null , unpack ( 'c1' , substr ( $Input , $Line ) ) ) ; $Line += 1 ;
$Output [ Map ] [ $Y ] [ Elevation ] = implode ( null , unpack ( 'c1' , substr ( $Input , $Line ) ) ) ; $Line += 1 ;
$Output [ Map ] [ $Y ] [ Unknown ] = implode ( null , unpack ( 'c1' , substr ( $Input , $Line ) ) ) ; $Line += 1 ;
}
?>
Note that it takes even more time if you use a custom function to implement the implode+unpack+substr functions.
Now... This method uses the FREAD function:
<?php
for ( $Y = 0 ; $Y < ( $width * $height ) ; $Y ++ ) {
$Output [ Map ] [ $Y ] = unpack ( 'c3' , fread ( $sc , 3 ) ) ;
}
?>
I recommend using the FREAD method instead of SUBSTR.
Another test!!! This method is 10x faster than the above. This does not use the FOR loop:
<?php
$Output [ Map ] [ Data ] = unpack ( 'c' . ( $width * $height ) , stream_get_contents ( $sc ) ) ;
?>
If you want to read files much faster, you should try to reduce the number of loops and use the unpack function to its simplest and robust method.