In: , , , ,
On: 2006 / 06 / 01 Viewed: 158979 times
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
PHP:
  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[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[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. }

(Download the full benchmark script)

Results

  PHP 4.4.2 PHP 5.1.2
straight, variables 0.0382 0.0269
straight, array 0.0510 0.0363
straight, constants 0.0552 0.03848
function call, variables 0.0382 0.0276
function call, array 0.0462 0.0331
function call, constants 0.0470 0.0388

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.

Conclusions

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.

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 :

PHP:
  1. if ($variable = 1) {
  2. // oops !
  3. }
  4.  
  5. if (VARIABLE = 1) {
  6. // easy to spot and won't work
  7. }

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

PHP:
  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.

12 Blablas

  1. 1
    BB2k France »
    replied, on 02/Jun/06 at 10:08 am # :

    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. 2
    Roland Hesz Hungary »
    wrote, on 02/Jun/06 at 10:11 am # :

    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. 3
    lf France »
    thought, on 06/Jun/06 at 11:57 pm # :

    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. 4
    PHP Sidor » Blog Archive » S... Sweden »
    pingback on 12/Aug/07 at 9:22 pm # :

    [...] ä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. 5
    Adriano Italy »
    replied, on 10/Oct/08 at 1:12 pm # :

    unbelievable!!!

    so? should we use variables?

  6. 6
    Johan Netherlands »
    said, on 26/Feb/10 at 2:34 pm # :

    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. 7
    Johan Netherlands »
    commented, on 09/Apr/10 at 8:33 am # :

    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. 8
    Ozh France »
    said, on 09/Apr/10 at 11:18 am # :

    Interesting take, Johan!

  9. 9
    Aleksej Ivanov Sweden »
    thought, on 16/Jan/11 at 11:24 pm # :

    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. 10
    Adriano United States »
    replied, on 25/Jan/11 at 10:56 pm # :

    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. 11
    Keilaron Canada »
    thought, on 30/Mar/11 at 8:42 pm # :

    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. 12
    Okonomiyaki3000 Japan »
    replied, on 16/Dec/11 at 11:29 am # :

    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.

Leave a Reply

Comment Guidelines or Die

  • HTML: You can use these tags: <a href=""> <em> <i> <b> <strong> <blockquote>
  • Posting code: Post raw code (no <> &lt; etc) within appropriate tags : [php][/php], [css][/css], [html][/html], [js][/js], [sql][/sql], [xml][/xml], or generic [code][code]
  • Gravatars: Curious about the little images next to each commenter's name ? Go to Gravatar.
  • Spam: Various spam plugins on patrol. I'll put pins in a Voodoo doll if you spam me.
  • I will mark as Spam test comments, all comments with SEO names (ie "My Cool Online Shop" instead of "Joe") or containing forum-like signatures.

Read more ?