Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How efficient is define in PHP?

Tags:

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;
like image 933
Prody Avatar asked Sep 29 '08 10:09

Prody


People also ask

How does define work in PHP?

The define() function defines a constant. Constants are much like variables, except for the following differences: A constant's value cannot be changed after it is set.

How constant is defined in PHP?

A constant is an identifier (name) for a simple value. The value cannot be changed during the script. A valid constant name starts with a letter or underscore (no $ sign before the constant name). Note: Unlike variables, constants are automatically global across the entire script.

How check is defined in PHP?

PHP isset() Function The isset() function checks whether a variable is set, which means that it has to be declared and is not NULL. This function returns true if the variable exists and is not NULL, otherwise it returns false.


2 Answers

'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).

like image 121
nazgul5 Avatar answered Oct 07 '22 21:10

nazgul5


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.

like image 33
Till Avatar answered Oct 07 '22 21:10

Till