20

C++ preprocessor #define is totally different.

Is the PHP define() any different than just creating a var?

define("SETTING", 0);  
$something = SETTING;

vs

$setting = 0;  
$something = $setting;
1
  • 1
    Be careful with this language pattern in PHP. Constants are "free" in C++ because all of the logic happens at compile time. They are expensive in PHP, both in terms of execution time and memory usage, since it happens at runtime. They should be used more sparingly than you would in C++. $something = 0; is the PHP equivalent performance wise (add a comment to describe the value). It's unfortunate but often the best option - that is what the C++ preprocessor does for you under the covers. Commented May 27, 2019 at 0:10

10 Answers 10

17

'define' operation itself is rather slow - confirmed by xdebug profiler.

Here is benchmarks from http://t3.dotgnu.info/blog/php/my-first-php-extension.html:

  • pure 'define'
    380.785 fetches/sec
    14.2647 mean msecs/first-response

  • constants defined with 'hidef' extension
    930.783 fetches/sec
    6.30279 mean msecs/first-response


broken link update

The blog post referenced above has left the internet. It can still be viewed here via Wayback Machine. Here is another similar article.

The libraries the author references can be found here (apc_define_constants) and here (hidef extension).

Sign up to request clarification or add additional context in comments.

Comments

5

In general, the idea of a constant is to be constant, (Sounds funny, right? ;)) inside your program. Which means that the compiler (interpreter) will replace "FOOBAR" with FOOBAR's value throughout your entire script.

So much for the theory and the advantages - if you compile. Now PHP is pretty dynamic and in most cases you will not notice a different because the PHP script is compiled with each run. Afai-can-tell you should not see a notable difference in speed between constants and variables unless you use a byte-code cache such as APC, Zend Optimizer or eAccelerator. Then it can make sense.

All other advantages/disadvantages of constants have been already noted here and can be found in the PHP manual.

Comments

5
php > $cat='';$f=microtime(1);$s='cowcow45';$i=9000;while ($i--){$cat.='plip'.$s.'cow';}echo microtime(1)-$f."\n";

0.00689506530762

php > $cat='';$f=microtime(1);define('s','cowcow45');$i=9000;while ($i--){$cat.='plip'.s.'cow';}echo microtime(1)-$f."\n";

0.00941896438599

This is repeatable with similar results. It looks to me like constants are a bit slower to define and/or use than variables.

Comments

4

Here are the differences, from the manual

  • Constants do not have a dollar sign ($) before them;
  • Constants may only be defined using the define() function, not by simple assignment;
  • Constants may be defined and accessed anywhere without regard to variable scoping rules;
  • Constants may not be redefined or undefined once they have been set; and
  • Constants may only evaluate to scalar values.

For me, the main benefit is the global scope. I certainly don't worry about their efficiency - use them whenever you need a global scalar value which should not be alterable.

1 Comment

the syntax and scope is obvious.. what I mean is performance wise
3

NOT efficient it appears. (And i'm basing all the assumptions here on one comment from php.net, i still haven't did the benchmarks myself.)

recalling a constant, will take 2x the time of recalling a variable.

checking the existence of a Constant will take 2ms and 12ms for a false positive!

Here's a benchmark from the comments of the define page in php's online doc.

Before using defined() have a look at the following benchmarks:

true                                       0.65ms
$true                                      0.69ms (1)
$config['true']                            0.87ms
TRUE_CONST                                 1.28ms (2)
true                                       0.65ms
defined('TRUE_CONST')                      2.06ms (3)
defined('UNDEF_CONST')                    12.34ms (4)
isset($config['def_key'])                  0.91ms (5)
isset($config['undef_key'])                0.79ms
isset($empty_hash[$good_key])              0.78ms
isset($small_hash[$good_key])              0.86ms
isset($big_hash[$good_key])                0.89ms
isset($small_hash[$bad_key])               0.78ms
isset($big_hash[$bad_key])                 0.80ms

PHP Version 5.2.6, Apache 2.0, Windows XP

Each statement was executed 1000 times and while a 12ms overhead on 1000 calls isn't going to have the end users tearing their hair out, it does throw up some interesting results when comparing to if(true):

1) if($true) was virtually identical 2) if(TRUE_CONST) was almost twice as slow - I guess that the substitution isn't done at compile time (I had to double check this one!) 3) defined() is 3 times slower if the constant exists 4) defined() is 19 TIMES SLOWER if the constant doesn't exist! 5) isset() is remarkably efficient regardless of what you throw at it (great news for anyone implementing array driven event systems - me!)

May want to avoid if(defined('DEBUG'))...

from tris+php at tfconsulting dot com dot au 26-Mar-2009 06:40

http://us.php.net/manual/en/function.defined.php#89886

Comments

1

Define is simple static sense, meaning its value can't be changed during runtime while variable is dynamic sense because you can freely manipulate its value along the process.

Comments

0

When I run speed tests, constants being set and dumped out run much a little faster than setting variables and dumping them out.

Comments

0

2020 update (PHP 7.2, AMD Ryzen9, Zend OpCache enabled)

summary: redefining the same constant is slow. checking and defining constants vs $_GLOBALS is about 8x slower, checking undefined constants is slightly slower. Don't use globals.

  • note: auto loaders and require once long paths are likely to be much larger problems than defines. (require once requires php to stat(2) every directory in the path to check for sym links, this can be reduced by using full paths to your file so the PHP loader only has to stat the file path 1x and can use the stat cache)

CODE:

$loops = 90000;
$m0 = microtime(true);
for ($i=0; $i<$loops; $i++) {
   define("FOO$i", true);
}
$m1 = microtime(true);
echo "Define new const {$loops}s: (" . ($m1-$m0) . ")\n";
// etc...

OUTPUT:

Define new const 90000s: (0.012847185134888)
Define same const 90000s: (0.89289903640747)
Define same super global 90000s: (0.0010528564453125)
Define new super global 90000s: (0.0080759525299072)
check same undefined 90000s: (0.0021710395812988)
check same defined 90000s: (0.00087404251098633)
check different defined 90000s: (0.0076708793640137)

Comments

-1

Main differences:

  • define is constant, variable is variable
  • they different scope/visibility

Comments

-3

Not sure about efficiency, but it is more than creating a var:

  • It is a constant: you can't redefine or reassign this SETTING.
  • If the define isn't found, $something is set to "SETTING", which is useful, for example, in i18n: if a translation is missing (ie. the corresponding define is the localization file), we see a big word in uppercase, quite visible...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.