Alfonso
Alfonso

Reputation: 37

Access a local PHP variable is faster that access a session PHP variable?

This is justa a performance question.

What is faster, access a local PHP variable or try to access to session variable?

Upvotes: 2

Views: 283

Answers (4)

webbiedave
webbiedave

Reputation: 48897

Superglobals will be slightly slower to access than non-superglobal variables. However, this difference will only be noticeable if you are doing millions of accesses in a script and, even then, such difference doesn't warrant change in your code.

$_SESSION['a'] = 1;
$arr['a'] = 1;

$start = 0; $end = 0;

// A
$start = microtime(true);
for ($a=0; $a<1000000; $a++) {
    $arr['a']++; 
}
$end = microtime(true);
echo $end - $start . "<br />\n";

// B
$start = microtime(true);
for ($b=0; $b<1000000; $b++) {  
    $_SESSION['a']++;   
}
$end = microtime(true);
echo $end - $start . "<br />\n";

/* Outputs: 
0.27223491668701
0.40177798271179

0.27622604370117
0.37337398529053

0.3008668422699
0.39706206321716

0.27507615089417
0.40228199958801

0.27182102203369
0.40200400352478
*/

Upvotes: 5

jwueller
jwueller

Reputation: 30996

I do not think that this makes any measurable difference. $_SESSION is filled by PHP before your script actually runs, so this is like accessing any other variable.

Upvotes: 7

Your Common Sense
Your Common Sense

Reputation: 157895

There is nothing performance-related in this question.
The only those performance questions are real ones, which have a profiling report in it.
Otherwise it's just empty chatter.

Actually such a difference will never be a bottleneck.
And there is no difference at all.

Upvotes: 0

d2burke
d2burke

Reputation: 4111

It depends, are you talking about setting the $_SESSION variable to a local variable for use throughout the file or simple talking about the inherent differences between the two types of variables?

One is declared by you and another is core functionality. It will always be just a smidge slower to set the $_SESSION variable to a local variable, but the differenceenter code here is negligible compared to the ease of reading and re-using.

Upvotes: 0

Related Questions