开发者

What is the point of replace function in Memcache?

What is the point of replace function in PHP mem开发者_Python百科cache if you can just use set? Even if there is a variable, set automatically replaces it, right?

Can you give me an example where it's better to use replace instead of set?

Thanks.


According to PHP.net:

Memcached::replace() is similar to Memcached::set(), but the operation fails if the key does not exist on the server.


Following on from ZoFreX's answer if you look at the comments here: http://www.php.net/manual/en/memcache.set.php

You will see the following:

Using set more than once for the same key seems to have unexpected results - it does not behave as a "replace," but instead seems to "set" more than one value for the same key. "get" may return any of the values.

This was tested on a multiple-server setup - behaviour may be different if you only have one server.

So really and truly replace() will look for an existing key first, and then replace it (if it exists), whereas set() will just add the key. I imagine it's always best to use replace() first considering it returns FALSE if the key is not found, in which case you'd use add() rather than set() since you know for sure the key doesn't exist. This ensures that you won't have any unintended mishaps. So you're code could be something like:

$replace = Memcached::replace($key, $var);
if ( ! $replace)
{
    $set = Memcached::add($key, $var);
}


Generally, replace should be used if the key is likely to be used frequently. Set/add/etc creates a brand new entry, and can lead to fragmentation and a lot of cleanup. Replace reuses the memory already allocated (if possible), and can be more stable and efficient. If it fails, using add/set will still work.


nope that's entirely wrong.

If you want to check and set a value you must use GETS + CAS.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜