我只是为了测试的目的拼凑了这些 - 因为我很好奇(我没有费心解析 XML,因为它比 json_encode() 还要慢):
<?php
header('Content-Type: text/plain;charset=utf-8');
set_time_limit(120);
//define variables
$iLoopCount = 10000;
$aTheArray = array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9");
$fStartTime = microtime(true);
//function to convert an array into a string used to create a PHP include file
function convertArrayToInclude(array $aIn) {
$sOut = 'array(';
foreach($aIn as $key => $value) {
$formattedKey = is_string($key) ? "'{$key}'" : $key;
$formattedValue = is_string($value) ? "'{$value}'" : $value;
$sOut .= "{$formattedKey} => {$formattedValue},";
}
$sOut = substr($sOut, 0, -1) . ');';
return $sOut;
}
//test serialize
for($i = 0; $i < $iLoopCount; $i++) {
file_put_contents("serialize.txt", serialize($aTheArray), LOCK_EX);
$aReadArray1 = unserialize(file_get_contents("serialize.txt"));
}
$fStopTime1 = microtime(true);
echo "serialize execution time ({$iLoopCount} iterations) : " . ($fStopTime1 - $fStartTime) . "s\n\n";
//test json_encode
for($i = 0; $i < $iLoopCount; $i++) {
file_put_contents("json_encode.txt", json_encode($aTheArray), LOCK_EX);
$aReadArray2 = json_decode(file_get_contents("serialize.txt"));
}
$fStopTime2 = microtime(true);
echo "json_encode execution time ({$iLoopCount} iterations) : " . ($fStopTime2 - $fStopTime1) . "s\n\n";
//test native using fixed data
for($i = 0; $i < $iLoopCount; $i++) {
file_put_contents("include.php",
'<?php $aReadArray3 = array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"); ?>'
, LOCK_EX);
include 'include.php';
}
$fStopTime3 = microtime(true);
echo "native include execution time with fixed data ({$iLoopCount} iterations) : " . ($fStopTime3 - $fStopTime2) . "s\n\n";
//test native using dynamic data
for($i = 0; $i < $iLoopCount; $i++) {
file_put_contents("include2.php",
'<?php $aReadArray4 = ' . convertArrayToInclude($aTheArray) . ' ?>'
, LOCK_EX);
include 'include2.php';
}
$fStopTime4 = microtime(true);
echo "native include execution time with dynamic data ({$iLoopCount} iterations) : " . ($fStopTime4 - $fStopTime3) . "s\n\n";
?>
点击刷新几次以查看相当一致的结果,但这就是您正在查看的内容:
序列化执行时间(10000 次迭代):4.6746249198914s
json_encode执行时间(10000次迭代):5.132187128067s
原生包括固定数据的执行时间(10000 次迭代):4.863872051239s
原生包括动态数据的执行时间(10000 次迭代):5.5474679470062s
所以,简而言之:如果您可以将 php 包含构建为字符串(本机固定数据),那么重复写入和包含该文件可能是最快的方法(见注释)。但是,如果您想包含一些完整性检查或将数组转换为可在该包含(本机动态数据)中使用的字符串,那么您将进入一个充满伤害的世界 - 您有功能和处理开销以及您的“自行开发”解决方案引入的任何/所有安全漏洞。这是最慢也是最糟糕的方式。
非常短:PHP 具有将变量存储为文本 (serialize()) 并检索它们 (unserialize()) 的函数......只需使用它们而不是试图重新发明轮子。
注意:使用serialize() 和fixed native data 之间的执行时间差异会随着每次刷新而摇摆不定,有时一个更快,有时另一个 - 本质上它对实际速度几乎没有影响。