tags:

views:

77

answers:

3

Are direct access and constant function which high-speed?( or less memory , cpu)

define("FOO","VAL");
print FOO;
print constant(FOO);

Could you give me a sample cord and the reason , so I am happy.

edit: I'm sorry Misunderstood it very much

print FOO or print constant(FOO)

Which is high-speed?

+2  A: 

Hi,

I'm not sure where you got your 2 arguments constant() construct, but the constant() function is a getter that only takes one argument: the constant name you want to retrieve.

define(), on the other hand, defines the value of a constant (setter). Comparing performance of those two functions doesn't make much sense as they accomplish completely different tasks.

Wadih M.
A: 

When you question speed of such simple operations, it's best to just do some quick&dirty benchmarking and compare the results.

define("FOO", "VAL");
$iterations = 10000;
$start_1 = microtime(true);
for ($i = 0; $i < $iterations; $i++) {
    print FOO;
}
$end_1 = microtime(true);
$time_1 = $end_1 - $start_1;

$start_2 = microtime(true);
for ($i = 0; $i < $iterations; $i++) {
    print constant('FOO');
}
$end_2 = microtime(true);
$time_2 = $end_2 - $start_2;

printf('"print VAL;" %d iterations: %.5F s', $iterations, $time_1);
print PHP_EOL;
printf('"print constant(\'FOO\');" %d iterations: %.5F s', $iterations, $time_2);

But I doubt that you'll see any significant difference between the two.

Stefan Gehrig
A: 

I think you misunderstand what constant() is being used for. If you only need to access a constant, do it directly: print FOO;

If you don't know what constant you want to access, you need constant(). I.e. you can do "variable variables" like this:

$name = 'var1';
$var1 = 'value something or other';
print $$name; // prints the value of $var1: 'value something or other' because:

${$name} -> ${"var1"} -> $var1 -> 'value something or other'

I.e. you are substituting the name of the variable through a variable.

You can't do this with constants:

$name = 'CONST1';
define('CONST1', 'value something or other');
print $name; // prints the value of $name: 'CONST1'

You'll need to use constant():

print constant($name); // prints 'value something or other'
deceze