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

后端 未结 2 1920
夕颜
夕颜 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:

    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('
    ');
    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);
    }
    

提交回复
热议问题