Memcache缓存居然不如直接File文件缓存?

原创
2016-07-30 13:30:59 781浏览

使用本地的环境测试10万次和 100万次 缓存的读写,测试环境和结果如下。

环境

Win7 x64 AMD7750双核 内存8G
Apache 2.4.9
PHP 5.5.12 ts vc11 
memcache 2.2.7

代码

functionconvert($size)
{$unit = array('b', 'kb', 'mb', 'gb', 'tb', 'pb');

    return @round($size / pow(1024, ($i = floor(log($size, 1024)))), 2) . ' ' . $unit[$i];
}

functioncacheFile($key)
{$dir = 'cache';
    if (!is_dir($dir) && !mkdir($dir)) {
        thrownewException(" can't make dir $dir");
    }

    $filepath = $dir . DIRECTORY_SEPARATOR . sprintf('%x', crc32($key));

    if (!(file_exists($filepath) && ($data = file_get_contents($filepath)) && !empty($data))) {
        $data = date('Y-m-d H:i:s');
        file_put_contents($filepath, $data);
    }

    return$data;
}


functioncacheMem($key)
{$mem = new Memcache();
    $mem->connect('127.0.0.1', 11211);
    $data = $mem->get($key);
    if (empty($data)) {
        $data = date('Y-m-d H:i:s');
        $mem->set($key, $data);
    }

    return$data;
}


$t1 = microtime(true);
$i = 0;
$limit = 1000 * 100; //10 万次$data = null;
while ($i $limit) {
//    $data = cacheFile($i);$data = cacheMem($i);
    $i++;
}
$timeUse = microtime(true) - $t1;
$arr = [
    'cost' => sprintf('%.7fs', $timeUse),
    'mem' => convert(memory_get_usage())
];
var_dump($arr);

结果 1万次

            花费时间           内存耗费
File        1.9sec250kb
Memcache    11sec250kb

结果 10万次

            花费时间    内存耗费
File94s        251.18KB
Memcache    超时120s 报错 

Memcache 10万次测试失败,报错内容如下

Warning: Memcache::connect(): in D:\localhost\speed.php online37
Warning: Memcache::get(): No servers added to memcache connection in D:\localhost\speed.php
Warning: Memcache::set(): No servers added to memcache connection in D:\localhost\speed.php online41
Fatal error: Maximum execution timeof120seconds exceeded in D:\localhost\speed.php online38

结论

memcache 用来做缓存却还没有 直接File文件缓存快,之所以做这个测试,是因为面试的时候我回答自己并没有使用这个memcache 来做缓存,直接使用File文件缓存(单台服务器),结果直接被技术官认定为是很菜鸟。但我通过这样的测试,虽然是在win下面,可为什么Memcahe性能还不如File ?
还是说我测试的方式存在错误? 求解 default.fu@foxmail.com

版权声明:本文为博主原创文章,未经博主允许不得转载。

以上就介绍了Memcache缓存居然不如直接File文件缓存?,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。