memcached:更快,执行添加(和检查结果)或获取(在返回false时设置) [英] memcached: which is faster, doing an add (and checking result), or doing a get (and set when returning false)
问题描述
这个问题的标题不清楚,但是代码和问题很简单.
The title of this question isn't so clear, but the code and question is straightforward.
假设我想每天向我的用户展示一次广告.为此,每次他们访问我网站上的页面时,我都会检查某个内存缓存键上是否存储了任何数据.如果是这样,请勿展示广告.如果不是,请在该密钥中存储值"1",有效期为86400.
Let's say I want to show my users an ad once per day. To accomplish this, every time they visit a page on my site, I check to see if a certain memcache key has any data stored on it. If so, don't show an ad. If not, store the value '1' in that key with an expiration of 86400.
我可以通过以下两种方式做到这一点:
I can do this 2 ways:
//version a
$key='OPD_'.date('Ymd').'_'.$type.'_'.$user;
if($memcache->get($key)===false){
$memcache->set($key,'1',false,$expire);
//show ad
}
//version b
$key='OPD_'.date('Ymd').'_'.$type.'_'.$user;
if($memcache->add($key,'1',false,$expire)){
//show ad
}
现在,似乎b更好了,它总是进行1次memcache调用. 但是,"add"与"get"的开销是多少?这些不是真正的比较...而我只是组成了这些数字,但是假设1个add〜= 1个集合〜= 5的努力,平均每天用户浏览5页:
Now, it might seem obvious that b is better, it always makes 1 memcache call. However, what is the overhead of "add" vs. "get"? These aren't the real comparisons... and I just made up these numbers, but let's say 1 add ~= 1 set ~= 5 get in terms of effort, and the average user views 5 pages a day:
a: (5 get * 1 effort) + (1 set * 5 effort) = 10 units of effort
b: (5 add * 5 effort) = 25 units of effort
始终执行添加调用是否有意义?这是不必要的微优化吗?
Would it make sense to always do the add call? Is this an unnecessary micro-optimization?
推荐答案
如果有人感兴趣的话,我在这里整理了一些快速而肮脏的代码进行测试:
Here's some quick and dirty code I whipped up to test this, if anyone is interested:
<?php
require('include.php');
$memcache = new Memcache();
foreach(Config::$CONFIG['memcache_server'] as $memcache_server){
$memcache->addServer($memcache_server,11211,false);
}
$iterations = 300;
$max_pages_per_visit = 25;
$time_now = microtime(true);
for($pages_per_visit = 1; $pages_per_visit<=$max_pages_per_visit; $pages_per_visit++){
foreach(array('gs','a') as $method){
$start = microtime(true);
for($x = 0; $x < $iterations; $x++){
$key = 'testmc'.$time_now.'_'.$pages_per_visit.'_'.$method.'_'.$x;
switch($method){
case 'gs':
for($y = 0 ; $y < $pages_per_visit; $y++){
if($memcache->get($key)===false){
$memcache->set($key,'1',null,5);
}
}
break;
case 'a':
for($y = 0 ; $y < $pages_per_visit; $y++){
$memcache->add($key,'1',null,5);
}
break;
}
}
$end = microtime(true);
$results[$pages_per_visit][$method] = $end - $start;
}
}
//print results
print('<pre>');
foreach($results as $pages_per_visit => $data){
$speed_diff = $data['gs'] - $data['a'];
$speed_percentage = round($speed_diff / $data['gs'] * 100,2);
echo($pages_per_visit.' pages : add is faster by :'.$speed_diff.' ('.$speed_percentage.')%'.PHP_EOL);
}
这篇关于memcached:更快,执行添加(和检查结果)或获取(在返回false时设置)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!