In: , , , ,
On: 2006 / 06 / 01
Shorter URL for this post: http://ozh.in/d9

I thought, and had been told, that using constants instead of variables in PHP was mostly a matter of speed : at run time, the engine replaces every occurrence of a constant with its hard-coded value, making code presumably faster than using variables that must be evaluated each time they are encountered. Or something like this.

Wondering how big or meaningless the incidence would be, and being the anal retentive useless benchmarks & statistics fan I am, I ran a few tests. With a surprise for me at the end. Bottom line : variables are faster ?!

Tests

To compare speed when processing some $variables, $arrays and CONSTANTS, I threw them twice into the silly formula ((sin(A * B + C))/D * (sqrt( log(E) * abs(F – 1/G)) / H)) * I

  1. straight processing
  2. function call and a global statement to access variables
  1. // straight processing, variables
  2. for($i=0;$i<$loop;$i++) {
  3.     $test = ((sin($val0 * $val1 + $val2))/$val6 * (sqrt( log($val3) * abs($val4 - 1/$val5)) / $val7)) * $val8;
  4. }
  5.  
  6. // straight processing, arrays
  7. for($i=0;$i<$loop;$i++) {
  8.     $test = ((sin($arrayval&#91;0] * $arrayval[1] + $arrayval[2]))/$arrayval[6] * (sqrt( log($arrayval[3]) * abs($arrayval[4] - 1/$arrayval[5])) / $arrayval[7])) * $arrayval[8];
  9. }
  10.  
  11. // straight processing, constants
  12. for($i=0;$i<$loop;$i++) {
  13.     $test = ((sin(VAL0 * VAL1 + VAL2))/VAL6 * (sqrt( log(VAL3) * abs(VAL4 - 1/VAL5)) / VAL7)) * VAL8;
  14. }
  15.  
  16. // function call, variables
  17. function testvar($loop) {
  18.     global $val0,$val1,$val2,$val3,$val4,$val5,$val6,$val7,$val8;
  19.     for ($i=0;$i<$loop;$i++) {
  20.         $test = ((sin($val0 * $val1 + $val2))/$val6 * (sqrt( log($val3) * abs($val4 - 1/$val5)) / $val7)) * $val8;
  21.     }
  22. }
  23.  
  24. // function call, array
  25. function testarr($loop) {
  26.     global $arrayval;
  27.     for ($i=0;$i<$loop;$i++) {
  28.         $test = ((sin($arrayval&#91;0] * $arrayval[1] + $arrayval[2]))/$arrayval[6] * (sqrt( log($arrayval[3]) * abs($arrayval[4] - 1/$arrayval[5])) / $arrayval[7])) * $arrayval[8];
  29.     }
  30. }
  31.  
  32. // function call, constants
  33. function testconst($loop) {
  34.     for ($i=0;$i<$loop;$i++) {
  35.         $sum = ((sin(VAL0 * VAL1 + VAL2))/VAL6 * (sqrt( log(VAL3) * abs(VAL4 - 1/VAL5)) / VAL7)) * VAL8;
  36.     }
  37. }
  38. &#91;/php]
  39.  
  40. (Download the full <a href="/download/benchmarking-constants-variables.php">benchmark script</a>)
  41.  
  42. <h2>Results</h2>
  43.  
  44. <table cellpadding="5" border="1">
  45. <tr><td>&nbsp;</td><td>PHP 4.4.2</td><td>PHP 5.1.2</td></tr>
  46. <tr><td>straight, variables</td><td>0.0382</td><td>0.0269</td></tr>
  47. <tr><td>straight, array</td><td>0.0510</td><td>0.0363</td></tr>
  48. <tr><td>straight, constants</td><td>0.0552</td><td>0.03848</td></tr>
  49. <tr><td>function call, variables</td><td>0.0382</td><td>0.0276</td></tr>
  50. <tr><td>function call, array</td><td>0.0462</td><td>0.0331</td></tr>
  51. <tr><td>function call, constants</td><td>0.0470</td><td>0.0388</td></tr>
  52. </table>
  53.  
  54. Hey, where is the supposedly speed advantage of constants ? Not only using variables is faster, but even arrays which I thought would perform worse consistently outperform constants.
  55.  
  56. <h2>Conclusions</h2>
  57.  
  58. I was not able to compare memory usage across these tests, but regarding speed I'm certainly disappointed to see how constants are doing. Of course, speed loss is probably negligible in almost if not all situations, but still.
  59.  
  60. Why use constants then ? Their only advantages over variables I can think of is that constant have a global scope so you can forget a global statement, and if you mistype a test (= instead of == or ===), it's safer to use a constant that cannot be redefined than a variable. Consider the following :
  61.  
  62. [php]
  63. if ($variable = 1) {
  64. // oops !
  65. }
  66.  
  67. if (VARIABLE = 1) {
  68. // easy to spot and won't work
  69. }

But this is slight advantage, and you're going safer anyway with a reverse syntax where typos generate a warning :

  1. if (1 == $variable) { // do stuff }

So, basically, I'm asking : why use constants ? Are you using them ?

Shorter URL

Want to share or tweet this post? Please use this short URL: http://ozh.in/d9

Metastuff

This entry "PHP : Variables vs Constants" was posted on 01/06/2006 at 9:29 pm and is tagged with , , , ,
Watch this discussion : Comments RSS 2.0.

13 Blablas

  1. BB2k says:

    lol at the antispam =)

    The difference between variables and CONSTANTS is really an advantage when you use compiled language since the CONSTANT is evaluated one time (at the compilation). this is the matter of the some optimisations algorithms that replace know variables in fonctions to speed up them.
    ie . if in C=A+3, A as a knonw value of 3 in this environnement (yes actually this is a constant, but only in a given envirronment) then the code will be transformed in C=6.

    In an intepreted language like php, the CONSTANt is replaced each time you run the code and then the optimisation is not so good. It should be better with the use of a pre-compiler like phpaccelerator (http://www.php-accelerator.co.uk/).

  2. Roland Hesz says:

    I use constants, mainly to avoid magic numbers, and for values that I use in a lot of places, but can change [urls, directories, filenames, etc.], so I won't forget to change one instance out of 10 :)

  3. lf says:

    j'aime bien ton blog, y a pleins de trucs ou je comprends rien, et en plus c'est en anglais, alors ça me rassure.

  4. […] är egentligen snabbast, är det nÃ¥gon störra skillnad? Jag sÃ¥g en bloggpost om detta, men kom fram till att jag ska fortsätta med arrayer eftersom det inte verkar vara nÃ¥gon större […]

  5. Adriano says:

    unbelievable!!!

    so? should we use variables?

  6. Johan says:

    what the..? And here i was thinking of changing a couple of variables to constants (alot of variables used for multi-language-stuff) to speed up the proces, even by a tiny bit… guess i won't now,

    anyhow, great job on this and thnx

  7. Johan says:

    You should also check the resources it takes, under default settings i ran the following test:

    <?php
    $i = 0;
    while(true){
    <<>>
    $i ++;
    echo $i, "_";
    }

    where <<>> is the one of the code below, which followed by the highest value of $i I got,

    define("var".$i, "X"); // highest value of $i = 2091796
    ${"var".$i} = "X"; // highest value of $i = 217845
    $var[] = "X"; // highest value of $i = 245070
    $var[][] = "X"; // highest value of $i = 84420

    While you showed that constants are the slowest, they are, by far, the least resource intensive,

    suprising is that arrays are also less resource intensive then normal variables, even though this effect weakens with multi-demensional arrays

  8. Ozh says:

    Interesting take, Johan!

  9. Aleksej Ivanov says:

    The test is completely incorrect. You've used math functions, that works with "coprocessor". Those functions cannot use constants so, the processor is performing a double job here. You are actually testing your processor.
    Try to test constants with integers or strings.

  10. Adriano says:

    Wow, I'm back to this page after years.

    You know, I believe that it all depends on the hardware, probably variables are more subject to RAM, while contants to hard drive and cpu.

    A

  11. Keilaron says:

    Interesting anti-spam, but what kind of voodoo doll can you use if you don't know who spammed you?

    Anyway, I realize this post is old, but I just ran a test seeing how fast constants and variables are *set*, nevermind retrieved or used, and felt like looking for similar information.
    The results: With a million statements each, constants only took 4 seconds, whereas variable took 44 MINUTES to be set…
    In other words, if you aren't going to change your values, you're saving a lot of time setting constants over variables.

  12. Okonomiyaki3000 says:

    Your test misses some key points that arise in reality.

    If you have certain values that will be the same throughout your application (configuration values for example) you will want to define them up front and then use them in various places, different scopes. To do this with variables, you'd either need to make them global (gross) or create a class or function for accessing them. Then you have the overhead of making a function call every time you need one. This is surely slower than accessing a constant.

    Also (and this is just speculation), I'd expect that constants will have the edge when you're using APC which you should be using at all times.

  13. Onur ?afak says:

    Here is the reason for the difference:
    1)Constants are typeless, so they are kept as strings. Try to wrap your variable contents with quotes, and you'll see they perform nearly the same, with constants performing slightly better.

    Also;

    2)As mentioned before, they don't eat working memory like variables do, they make considerable difference in resource usage especially in big projects.

    3)They are constant, they protect you from changing them by mistake, in an included file or somewhere.

    4)Using them semantically states that they are not touched by the application, increasing the readability. So you can better understand the internals of a new script you are unfamiliar with, in less time, without wondering the current content of a variable.

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>
Gravatars: Curious about the little images next to each commenter's name ? Go to Gravatar and sign for a free account
Spam: Various spam plugins may be activated. I'll put pins in a Voodoo doll if you spam me.

Read more ?