Does adding Memcached/APC require writing codes again?
I'm planing to add APC or MEMCACHED to my PHP code ! my question is does it require to rewr开发者_开发知识库ite all the code ? as i looked in to PHP Manual and there i got this !
function get_foo(foo_id)
foo = memcached_get("foo:" . foo_id)
return foo if defined foo
foo = fetch_foo_from_database(foo_id)
memcached_set("foo:" . foo_id, foo)
return foo
end
So, for storing the variable i need to do memcached_set(...) or it's like that i add the plugin and get the performance boost !
I have no idea on APC / Memcache, so any discussion on this is welcome
With APC, you first get an opcode cache -- for that part, you having nothing to modify in your code : just install the extension, and enable it.
The opcode cache will generally speed up things : it prevents the PHP scripts from being compiled again and again, by keeping the opcodes -- the result of the compilation of the PHP files -- in memory.
Then, APC and memcached allow one to store data in memory ; typically, this is used to cache the result of long/costly operations (like complex SQL queries, webservices calls, ...).
About that, there is no magic : you will have to code a bit, to store data into the cache, and fetch it from it -- doing the long/costly operation if the data is not in cache, or the cache has expired.
Here are a couple of questions/answsers that might get you some additional informations :
- what is the easiest way for opcode caching with PHP/Apache ?
- What is a bytecode cache and how can I use one in PHP?
- How much more efficient is php_apc than memcached?
First you will get a performance boost just for installing APC. When a script is executed it is run through Zend_Compile that turns your PHP code into OPCODES that it then runs through Zend_Execute to run. The process of turning PHP into OPCODES is identical every time the page loads, so doing it again next time is a waste. APC (Alternative PHP Cache) saves those opcodes in memory, so next time it can skip that step and make the page load faster.
When it comes to caching in your script, you will need to make some changes. You can make these changes incrementally over time, getting a bit more performance each time, so you don't need to worry about doing it all at once. If you've got a single server I'd use APC, if you may have multiple servers in the future I'd go with Memcache.
Low hanging fruit for performance improvements:
- Find things that are loaded a lot, like your home page. Re-write that controller with an extra function that checks to see if there's data in the cache, and uses it if it's available. If not, load it the old way, and store it in the cache. Remember that you can put arrays and objects in both of these data stores, so it should be pretty quick to do.
- Look at database queries that take a long time to execute, cache them as well.
- Find other computationally expensive things to cache, these will depend a lot on your specific application.
精彩评论