note 113359 added to function.unpack

From: Date: Tue, 01 Oct 2013 11:03:25 +0000
Subject: note 113359 added to function.unpack
Groups: php.notes 
Request: Send a blank email to php-notes+get-196435@lists.php.net to get a copy of this message
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 ; } //The average microtime was: 2.9 sec ?> 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 ) ) ; } //Average microtime was: 0.7 sec ?> 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 ) ) ; //Average microtime: 0.08 - 0.05 sec ?> 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. ---- Server IP: 69.147.83.199 Probable Submitter: 203.134.47.163 ---- Manual Page -- http://php.net/manual/en/function.unpack.php Edit -- https://master.php.net/note/edit/113359 Del: integrated -- https://master.php.net/note/delete/113359/integrated Del: useless -- https://master.php.net/note/delete/113359/useless Del: bad code -- https://master.php.net/note/delete/113359/bad+code Del: spam -- https://master.php.net/note/delete/113359/spam Del: non-english -- https://master.php.net/note/delete/113359/non-english Del: in docs -- https://master.php.net/note/delete/113359/in+docs Del: other reasons-- https://master.php.net/note/delete/113359 Reject -- https://master.php.net/note/reject/113359 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#196435) next »