经常看到两种快捷的配置文件取值方法:
1、C('config_test','key');
2、test::load_config('config_test','key');
第一种方法用函数的形式,内置static变量获取key对应的value,而第二种则使用类的静态方法获取值。
两种代码哪一种的效率更高呢? 一只搞不清楚,晚上做了一个实验。
<?php
header('Content-type:text/html;charset=utf-8');
$total = 1000000;
G('function_start');
M('function_start');
for ($i=0;$i<$total;$i++){
$val = C('config_test','key');
}
echo '函数取值了',$total,'次,总共话费时间:',G('function_start','function_end'),'内存消耗:',M('function_start','function_end'),'<br />';
G('class_start');
M('class_start');
for ($i=0;$i<$total;$i++){
$val = test::load_config('config_test','key');
}
echo '类静态方法取值了',$total,'次,总共话费时间:',G('class_start','class_end'),'内存消耗:',M('class_start','class_end'),'<br />';
function G($start,$end='',$dec=3) {
static $_info = array();
if(!empty($end)) { // 统计时间
if(!isset($_info[$end])) $_info[$end] = microtime(TRUE);
return number_format(($_info[$end]-$_info[$start]),$dec);
} else { // 记录时间
$_info[$start] = microtime(TRUE);
}
}
function M($start,$end='') {
static $_info = array();
if(!empty($end)) { // 统计时间
if(!isset($_info[$end])) $_info[$end] = memory_get_usage();
return ($_info[$end]-$_info[$start]);
} else { // 记录时间
$_info[$start] = memory_get_usage();
}
}
function C($file,$key='',$default=''){
static $config;
if(!isset($config[$file])){
$config[$file] = include($file.'php');
}
if (empty($key)) {
return $_config[$file];
} elseif (isset($_config[$file][$key])) {
return $_config[$file][$key];
}else{
return $default;
}
}
class test{
public static $_config;
public static function load_config($file, $key = '',$default='') {
if (isset(self::$_config[$file])) {
if (empty($key)) {
return self::$_config[$file];
} elseif (isset(self::$_config[$file][$key])) {
return self::$_config[$file][$key];
} else {
return $default;
}
}
$path = $file.'.php';
if (file_exists($path)) {
self::$_config[$file] = include $path;
}
if (empty($key)) {
return self::$_config[$file];
} elseif (isset(self::$_config[$file][$key])) {
return self::$_config[$file][$key];
}else{
return $default;
}
}
}
?>
100万次的时候的结果如下:
函数取值了1000000次,总共话费时间:1.125内存消耗:728
类静态方法取值了1000000次,总共话费时间:2.052内存消耗:1040
10万次的结果如下:
函数取值了100000次,总共话费时间:0.132内存消耗:728
类静态方法取值了100000次,总共话费时间:0.200内存消耗:1040
两个结果可以了么?
貌似类的静态方法速度比较挫。
那下次要静态全局取文件用啥好?当然用函数。