memcached: which is faster, doing an add (and checking result), or doing a get (and set when returning false)

后端 未结 2 1906
夕颜
夕颜 2021-01-12 19:18

The title of this question isn\'t so clear, but the code and question is straightforward.

Let\'s say I want to show my users an ad once per day. To accomplish this,

相关标签:
2条回答
  • 2021-01-12 19:45

    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);
    }
    
    0 讨论(0)
  • 2021-01-12 19:55

    If you know the key exists, it would probably be faster to do an increment operation and look at the results. This is similar to the rate limiting and throttling problems that people encounter; you could probably craft a good Google search knowing that.

    0 讨论(0)
提交回复
热议问题