类的静态方法与函数静态存储变量的效率比较

经常看到两种快捷的配置文件取值方法:

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

两个结果可以了么?

貌似类的静态方法速度比较挫。


那下次要静态全局取文件用啥好?当然用函数。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值