|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
[2001-10-21 02:08 UTC] sniper@php.net
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Fri Oct 24 06:00:01 2025 UTC |
I have a php script that displays a report. The report is based on data retrieved from a database (MySQL in this case but can be alomst any). I am doing some summation on the data retrieved. I was attempting to add values to the array and found that my script was running fairly slow (30 seconds to process 89 records) Through alot of trial and error I determined the following problem. If you have an empty array i.e. $somearray = array(); and you try to add a value to an element i.e. $somearray[0] += 100; it takes considerably longer for php to do this than if we have the following example $somearray = array(0); $somearray[0] += 100; It appears that php has some problems adding to a value in an array if the item does not already exist. By Initialising my arrays in my script to 0 I cut the execution time for the script from 30 seconds to 4 seconds. This script was only trying to add into none existant array elements 120 times in my script and yet it took almost 26 seconds to do this. If this is not a bug it should atleast be brought to peoples attention that this can cause performance problems in some situation. Here is a complete example script with timer <?php function getmicrotime(){ list($usec, $sec) = explode(" ",microtime()); return ((float)$usec + (float)$sec); } // Create the array // $add_test = array(); // Start the first pass timer // $firstpassstart = getmicrotime(); // run through the array the first time // for ($loopcounter = 0; $loopcounter <= 100; $loopcounter++) { // Add 1 to each element // Note none of these elements exist $add_test[$loopcounter] += 100000; } // Stop the first pass timer // $firstpassfinish = getmicrotime(); $firstpass = ($firstpassfinish - $firstpassstart); // Start the Second Pass timer // $secondpassstart = getmicrotime(); // run through the array a second time // for ($loopcounter = 0; $loopcounter <= 100; $loopcounter++) { // Add 1 to each element // Note these elements all exist $add_test[$loopcounter] += 100000; } // Stop the Second Pass timer // $secondpassfinish = getmicrotime(); $secondpass = ($secondpassfinish - $secondpassstart); // Display the results // echo "First Pass took $firstpass seconds<br>\n"; echo "Second Pass took $secondpass seconds<br>\n"; ?> When I run this the first pass is 5 times slower than the second pass. While the times I get for this script are small (First pass takes 0.004 seconds) in some situations this can be much worse.