我想测量 php 文件中一堆常量的确切加载时间。我选择了 4 种方法:
- 使用键值对数组(在 php 文件中返回数据数组)
- 使用一个包含常量的类
- 定义
- json(将 json_encoded 值写入文件并使用 file_get_contents 和 json_decode 加载它们)
首先,我使用这些方法创建了 4 个不同的文件,然后用 5000 个随机名称和值对填充它们(所有的值相同)。
我尝试在 PHP 中加载它们并使用microtime
函数来测量加载时间,但结果似乎有点奇怪!这是我的test.php
文件:
// array
$time['array']['start'] = microtime(true);
$config_a = include('conf_array.php');
$time['array']['end'] = microtime(true);
// class
$time['class']['start'] = microtime(true);
include('conf_class.php');
$config_c = new Config();
$time['class']['end'] = microtime(true);
// define
$time['defin']['start'] = microtime(true);
include('conf_define.php');
$time['defin']['end'] = microtime(true);
// json
$time['json']['start'] = microtime(true);
$config_j = json_decode(file_get_contents('conf_json.json'));
$time['json']['end'] = microtime(true);
foreach ($time as $name => $item) {
echo $name . ": " . (($item['end'] - $item['start']) * 1000) . " units.";
}
当我test.php
使用一组新生成的文件加载时,我会得到以下结果:
Array: 7.9629421234131 units.
Class: 6.5279006958008 units.
Defin: 19.877910614014 units.
Json: 4.4741630554199 units.
但是当我点击刷新按钮(F5)时,结果会改变!以下是刷新页面后相同示例的结果:
Array: 1.7659664154053 units.
Class: 2.467155456543 units.
Defin: 6.4060688018799 units.
Json: 4.9409866333008 units.
然后,顺序不会再改变了。当您多次加载 php 文件(除 json 之外的所有文件)时,它们似乎会加载得更快。如果我重新启动 apache(连同 PHP),也会发生同样的事情。
我想知道为什么会这样?!它与某种缓存有关吗?