Online
 
Friday, 09 January 2009
 
 
More article:
Related Content:

Your Ad Here

Optimizing Your PHP Scripts
 
Article Index
Optimizing Your PHP Scripts
Page 2
Page 3
Page 4
Page 5
Page 6
Page 7
Page 8
Page 9
Page 10
Page 11
Page 12
 
Invariant Loop Optimization

Looping in any programming language is an absolutely fundamental tool. However, this same technique that makes our lives so much easier can also result in substantially slower code. For this illustration, consider a script that takes a string and creates a new shuffled version of that string. One solution to this problem is as follows:

                $shuffled = array();

for($i = 0; $i < (strlen($string)-1); $i++) {
$shuffled[] = $string[rand(0, (strlen($string)-1))];
}
$new_string = implode($shuffled);

Notice that in this solution the strlen() function is called for every iteration of the for loop. In this case, the value returned from strlen() is constant for this loop (invariant) and needs to be calculated only once. Method #2 removes the strlen() calculation from the loop itself by calculating the value once and storing the result in a variable:

                                 $str_len = strlen($string) -1 ;
$shuffled = array();

for($i = 0; $i < $str_len; $i++) {
$shuffled[] = $string[rand(0, $str_len)];
}
$new_string = implode($shuffled);

When profiling these two methods against each other, we find the following results:

NOTE

For this particular code snippet, it is notable that the amount of time taken to execute the segment was so small that profiling information was inaccurate. To provide more accurate profiling information, both methods were executed 100 times.


Method one took 0.04446005821228 seconds.
Method two took 0.035489916801453 seconds.

Method two was faster than Method one by 20.18%


Tags: Add more tags...,
This entry was posted on . You can follow any responses to this entry through the RSS 2.0 feed. You can leave a comment. Tags: Simple PHP, Pear, Easy PHP, PHP Tutorial, PHP MySQL, XSLT, Sap Tutorial, CSS Tutorial, XSL FO Java, SQL Tutorial.
Users' Comments (0)

Comment an article
  Name
  E-mail
   Title
Available characters: 4000
 Notify me of follow-up comments
This image contains a scrambled text, it is using a combination of colors, font size, background, angle in order to disallow computer to automate reading. You will have to reproduce it to post on my homepage
Enter what you see:

No comment posted

Wallpaper 63
Statistic


Last Post

 
Top! Top!