Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>After some reading, writing and testing I got something:</p> <pre><code>function inc(&amp;$var){ if (isset($var)) $var++;else $var=1; } </code></pre> <p>and thought I struck gold, but let's see the tests first...</p> <h2>Test code:</h2> <pre><code>$a=array(); // Pre-Fill array code goes here for($i=1;$i&lt;100000;$i++) { $r=rand(1,30000); //increment code goes here } // Remove extra keys from array with: //foreach ($a as $k=&gt;$v) if ($v==0) unset($a[$k]); </code></pre> <p>Execution times: <em>(for informative purposes only)</em></p> <pre><code>inc($a[$r]) 1.15-1.24 @$a[$r]++ 1.03-1.09 $a[$r]=array_key_exists($r,$a)?$a[$r]++:1; 0.99-1.04 $a[$r]=!empty($a[$r])?$a[$r]++:1; 0.61-0.74 if (!empty($a[$r])) $a[$r]++;else $a[$r]=1; 0.59-0.67 $a[$r]=isset($a[$r])?$a[$r]++:1; 0.57-0.65 if (isset($a[$r])) $a[$r]++;else $a[$r]=1; 0.56-0.64 //with pre-fill $a=array_fill(0,30000,0); +0.07(avg) for($i=1;$i&lt;=30000;$a[$i++]=0); -0.04(avg) //with pre-fill and unset $a=array_fill(0,45000,0); +0.16(avg) for($i=1;$i&lt;=45000;$a[$i++]=0); +0.02(avg) </code></pre> <h2>Conclusions:</h2> <ul> <li><code>@</code> is of course the fastest to type and I don't see any problem in using it <strong>in this case</strong> but feel free to check this question also: <a href="https://stackoverflow.com/q/136899/731947">Suppress error with @ operator in PHP</a></li> <li>completely suppressing errors (before the loop and enabling errors after the loop) via <code>ini_set()</code> is worse than all on performance</li> <li><code>inc()</code> looks nice and clean, easy to type and does checking instead of suppressing, but calling it looks to be even slower than <code>@</code></li> <li><code>isset()</code> is slightly faster than <code>empty()</code>, but both perform fairly the same</li> <li>interestingly using <strong>shorthand</strong> <code>if</code> statements is <strong>slightly slower</strong>!</li> <li>best results achieved when pre-filling the array. Even if length is unknown a good prediction would be still slightly faster on a huge dataset</li> <li>strangely, <code>array_fill()</code> takes slightly longer than <code>for</code> ?!?!</li> </ul> <h2>RFC</h2> <p>I don't consider this answer 100% complete, although, for now it looks like <code>isset()</code> is the fastest and <code>@</code> the laziest.<br> Any comments and ideas are appreciated!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload