TLDR:Pass by parameter
= $GLOBALS element
>>>global $var
有疑問時,測試!下面的結果表明:
- 通過參數傳遞1MB的字符串是遠遠大於全球$ VAR
- 通過參數傳遞1MB的字符串裁判更好的性能是大致相等的高性能爲使用$ GLOBALS [「變種」]
- 以下面的方式使用全局$ var似乎與內存中的GC引用計數混亂,而且速度很慢。顯然,不要使用全局$ var來處理這樣的情況。
結果(見下文進一步代碼):
時間是秒過去時,存儲器存儲潛在泄漏。
$ php -e test.php
Pass value by parameter
Time: 0.20166087150574s
Memory: 0
Global var reference
Time: 70.613216876984s
Memory: 1048576
GLOBALS array reference
Time: 0.22573900222778s
Memory: 0
測試代碼:
<?php
$baseVar = str_repeat('x', 1000000);
$GLOBALS['myVar'] = $baseVar;
function testfunc_param($paramVar) {
$localVar = $paramVar;
return $localVar;
}
function testfunc_global() {
global $myVar;
$localVar = $myVar;
return $localVar;
}
function testfunc_globalsarray() {
$localVar = $GLOBALS['myVar'];
return $localVar;
}
// Testing passing value by parameter
memory_get_usage(); // in case this procs garbage collection
$memoryStart = memory_get_usage(true);
$timeStart = microtime(true);
for ($i = 0; $i < 1000000; $i++) {
testfunc_param($baseVar);
}
$timeEnd = microtime(true);
$memoryEnd = memory_get_usage(true);
print "Pass value by parameter\nTime: ".($timeEnd - $timeStart)."s\nMemory: ".($memoryEnd-$memoryStart)."\n\n";
// Testing reference to global variable
memory_get_usage(); // in case this procs garbage collection
$memoryStart = memory_get_usage(true);
$timeStart = microtime(true);
for ($i = 0; $i < 1000000; $i++) {
testfunc_global();
}
$timeEnd = microtime(true);
$memoryEnd = memory_get_usage(true);
print "Global var reference\nTime: ".($timeEnd - $timeStart)."s\nMemory: ".($memoryEnd-$memoryStart)."\n\n";
// Testing reference to global variable via $GLOBALS
memory_get_usage(); // in case this procs garbage collection
$memoryStart = memory_get_usage(true);
$timeStart = microtime(true);
for ($i = 0; $i < 1000000; $i++) {
testfunc_globalsarray();
}
$timeEnd = microtime(true);
$memoryEnd = memory_get_usage(true);
print "GLOBALS array reference\nTime: ".($timeEnd - $timeStart)."s\nMemory: ".($memoryEnd-$memoryStart)."\n\n";
我不認爲這會令多大的差別,以及代碼的可讀性是很重要的。即使傳遞變量稍微慢一點(我不知道是否是這樣),通常應該避免使用全局變量。 – halfer