访问本地PHP变量访问会话PHP变量的速度更快吗?

Alf*_*nso 2 php

这只是一个性能问题.

什么是更快,访问本地PHP变量或尝试访问会话变量?

jwu*_*ler 7

我不认为这会产生任何可衡量的差异.$_SESSION在脚本实际运行之前由PHP填充,因此这就像访问任何其他变量一样.


web*_*ave 5

与非超全局变量相比,超全局变量的访问速度将稍慢。但是,只有当您在脚本中进行数百万次访问时,这种差异才会显着,即使这样,这种差异也不能保证您的代码有所更改。

$_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
*/
Run Code Online (Sandbox Code Playgroud)