I’m starting to learn about using Memcached with PHP and I was wondering; is there a point at which you should start using it? Is it always more efficient to cache data or does it only become effective once your site gets a certain number of hits? Presumably there is an overhead associated with Memcached, so when does the speed benefit outweigh this?
Thanks in advance for any advice.
You should start using memcached when not using it starts to affect your site / server.
So when you just have 100 visitors a day and your site still responds quickly, don’t bother using it.
But when you have running times somewhere near 200ms or more per page, and the site feels slow too, you should look out for the bottlenecks using some PHP profiler (XDebug integrates one that you can use in combination with WinCacheGrind or KCacheGrind).
Especially caching database requests should save you some load time.
The #1 rule when it comes to performance optimization is: Don’t optimize until you need to!
If you don’t have performance problems, then you don’t need to optimize. Other good rules include:
Don’t optimize until you’re done writing the application. You rarely know where real-world performance problems will crop up while developing, and it’ll only make your code sloppier and more difficult to modify when you need to make a change down the road.
Use a profiler or some other way of measuring specific chunks of code to actually measure what’s taking a long time, and optimize those sections. Don’t just guess at what’s taking a long time. Actually measure it.
If you’re using MySQL as database, run show processlist command on MySQL console during the peak time. If there’re many queries from the PHP side waiting for more than 500ms, it’s time you turned to memcached.
First think about what/when/if to cache, before you think about if you should be using Memcached to do the caching.
When you have some “object” that is used to respond to lots of requests that takes lots of database reads to create. And your site cannot keep up with its load due to recreating that “object” offen. You also need a nice well-defined key for the item you are caching.
The “object” you are caching must be read a lot more often then the database rows used to create it is changed, otherwise the benefit of cache is likely to be less the cost of managing the cache after time a bit of data is changed.
Caching single database rows will not give you match benefit.