MikoAndras.hu/en

Personal pages for Andras MIKO

Code optimizations in PHP

Code v4 – reverse array-management

We have run through the array-management functions before as well because they were the most expensive, and this will continue. But for the modifications below we have to clear a few things before:

  • the variation-array stores strings
  • we compare those to each other with the in_array() function
  • these strings are unique throughout arrays (appearing only once in each)
  • we do not need to know the value or the position of the match, but that there is or is not
  • used php version can work with associative arrays

Attacked codepart

          if (! in_array($actual_variation, $variation_cache[$passengers])) {
            $variation_cache[$passengers][] = $actual_variation;
          }

in_array() starts at the beginning of the array and compares elements until it reaches the end of it. Only case it terminates before the end is when it finds a match before, in that case it returns with the value true. If there is no matching value it goes through all the values and only then gives the false value.

With the conditions mentioned above we get to create an index on the array, so helping the mathing procedure. We use the associative type for that, because the keys on that will be indexed by default by the php engine.

Replacing code

          if (! isset($variation_cache[$passengers][$actual_variation])) {
            $variation_cache[$passengers][$actual_variation] = $actual_variation;
          }

Modification is the only part, that we do not use an automatic number on the array, but use the same string for key and value as well. On the comparison we look if a specific key exists or not, and this – thanks to the indexing – will allow us a really fast lookup.

Resource-usage of the version:

Calculation time v4

Calculation time v4

Memory usage v4

Memory usage v4

In text:

  • Calculated in 1 second: 92 person
  • Calculated in 30 seconds: ? person (stops because of memory limit)
  • 25 arriving guests: 0.005 seconds
  • 128MB memorylimit: at calculating 121 guests

Rating: truly remarkable.

We have reached a point where we cannot get a hold on the code with just reading it, we have hacked a bit from all parts by now. These moments call for profiler-tools.

I have called for the XDebug + KCachegrind double.

Pages: 1 2 3 4 5 6 7

, , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

*

*

You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>