php cache class? - php

My big problem is I need to create some objects, and I found that just to include() their class itself needs time. I tried to use serialize(), unserialize() to speed up object creations, but it only helped some milliseconds, the classes themselves still needs to be required. But this require itself causes delay. Is there a way to cache "classes" ?

There are ways to speed this up like bytecode caching, but it's often not an option on shared hosting, creates a new dependency and should not be necessary at all for a small project - smartening up the code will probably fix the problem.
Look exactly at what is being included, and whether all of it is needed all the time.
Here is some advice on how to split code into more manageable chunks: How can I improve the performance of 'include()s' in PHP?
Look into PHP autoloading: http://php.net/manual/en/language.oop5.autoload.ph

Yes, is called APC (Alternative PHP Cache) :- http://php.net/manual/en/book.apc.php
Is a native PHP modules, compiled into PHP compiler
Second thought, classes / object is cacheable,
but not those resources like XML object, database result object

If you don't want to write your class. Try phpFastCache.com, it's good and simple for beginner.
Okay, If you want to write a class, and cache your code, you can use APC, MemCached, WinCache. Here is the class for it. However, optcode caching only reduce database call or save API transactions for your website. IT IS NOT GONNA SPEED UP THE WAY YOU CODE. It's only speed up your page load by saving your time on connect and get information from database or API / Functions.
You have to try PHPaccelerators or Varnish. These are cache php code, and your server won't complite it again until it is needed.
If you don't want any of them, create a RAM DISK, and just serialize(), unserialize() into files of the RAM DISK. RAM is always faster than DISK.

Related

PHP Includes and Memory

I hope this is not a completely stupid question. I have searched quite a bit for an answer, but I can't find (or recognise) one exactly on point.
I understand that functions in PHP are not parsed until actually run. Therefore, if I have a large class with many functions, only one of which requires a large include file, will I potentially save memory if I only include the "include file" within the function (as opposed to at the top of the class file)?
I presume that, even if this would save memory, it would only do so until such time as the function was called, after which the memory would not be released until the current script stopped running?
Many Thanks,
Rob
I love this saying: "Make it work and then, if needed, make it fast." -some good programmer?
In most cases you would probably be better off focusing on good OOP structure and application design then speed. If you server is using something like Zend Optimizer having all your methods in a single file won't make any difference since it is all pre-compiled and stored in memory.(It's more complicated then this but you get the idea)
You can also load all your include files when apache starts. Then all the functions are loaded in memory. You wouldn't want to do that while developing unless you like to restart Apache every time you make a code change. But when done on production servers it can make a huge difference. And if you really want to make things fast you can write the code in C++ and load it as a module for Apache.
But in the end... do you really need that speed?
Yes it will, but be sure that the function doesn't depend on any other functions included in the parent. The memory consumption is also dependent on a couple things, from the size of the file itself to the amount of virtual memory it requires with variable setting and proper garbage collection protocols.
If the function is inside a class, it's called a method, and it might depend on its class to extend another class.
Just some things to consider. Always include the bare minimum.
Don't save memory on such cases unless you really need it, save development time. Memory is usually cheap but development/supoort time isn't. Use php opcode cacher like eAccelerator or APC, it will increase speed of execution because all files will be pre-compiled and stored in memory.

What is the Best way to "Store" data for quick and repetitous retrieval

Fictious Background
I get 100 hits a minute for "the hottest car"
The hottest car always changes by the minute and its currently: "A Pinto"
Everytime I receive what the current hottest car is, I save it into a MySQL Database.
Situation
Everytime I get a hit for "Whats the hottest car", I need to return the answer. I feel confident that retrieving the answer from a file vs. a DB will be faster and less work for the processor due to PHP storing the file into memory. My concern is that if I get a new file, how do I make sure i'm returning the information in the new file and not the old information stored in memory.
P.S. If my assumptions are wrong and there is a faster way, please let me know.
Thanks
Be careful with your assumptions. It can be tempting to assume that file access is faster, since you just have to read a file instead of connect to, query, and retrieve from a database. But bear in mind that databases are designed from the ground up for this kind of fast access to rapidly-changing information, and they have a lot of optimizations built in.
So look into caching, it is often a win, but I would not assume that file access is always faster. You can of course profile the different approaches to see if you have a bottleneck.
Your assumption is most probably going to be invalid. MySQL has a query cache which keeps your query in memory. Even if not I don't think you should but using the filesystem or unless you are using /dev/shm because that's mapped to memory. I would use a library like Cache_Lite to ease the pain of caching.
But if you want to make your site really fast you should install APC. You should always install APC if you want your website to be fast because caching the compiled bytecode of PHP scripts. Or use an in-memory databases redis or memcached, because these are even better in memory databases. redis is the easiest to install only using make and you don't need any ROOT permission either.
P.S: You should check out this redis tutorial because it is really powerful in-memory database.
I'm pretty sure it would be a bad idea to store that information in a file. The biggest problem is file read locks. If one person tries to get the file while another person is getting it, there's a conflict and a fatal error.
You really should go the database route, especially if you're planning on persisting the older "hottest cars". And if performance is a concern, you should look into PHP caching (see #Andrew's comment).
Instead of using a DB/file it should be the fastest way if you directly access the memory: http://www.php.net/manual/en/book.shmop.php
Memcache, memcache, memcache!
http://us2.php.net/memcached

cache methods in php?

what are the available cache methods i could use in php ?
Cache HTML output
Cache some variables
it would be great to implement more than one caching method , so i need them all , all the available out there (i do caching currently with files , any other ideas ?)
Most PHP build don't have a caching mechanism built in. There are extensions though that can take care of caching for you.
Have a look at APC or MemCache
If you are using a framework, then most come with some form of caching mechanism that you can use e.g. Zend Framework's Zend_Cache.
If you are not using a framework then the APC or Memcache as Pelle ten Cate mentioned can be used. The correct approach to use does depend in your situation though, do you have your website or application running on more than server and does the information in the cache need to be shared between those servers? (if yes then something like memcache is your answer, or maybe a database or distributed NoSQL solution if you are feeling brave).
If you code is only running on the one server you could try something simple like serializing your variables, and writing them to disk, then on every request afterwards, see if the files exists, if it does, open it and unserialize the string into the variable you need.
This though is only worth it if it would take a long time to generate the varaible normally,
(e.g longer than it would to open,read,unserialize the file on disk)
For HTML caching you are generally going to get the most mileage from using a proxy like Varnish or Squid to do it for you but i realise that this may not be an option for you.
If its not then you could the write to disk approach i mentioned above, and save chunks of HTML to files. look in the PHP manual for ob_start and its friends.
Since every PHP run starts from scratch on page request, there is nothing that would persist between calls, making cacheing moot.
Well, that's the basic view. Of course there are ways to implement a caching, sort of - and a few packages and extensions do so (like Zend Extensions and APC). However, you should have a very close look whether it actually improves performance. Other methods like memcache (for DB results), or switching from PHP to e.g. Java will often yield better results.
You can store variables in the $_SESSION, but you shouldn't keep larger HTML there.
Please check what you are actually trying to do. "Bytecode cacheing" (that is, saving PHP parsing time) needs to be done by the PHP runtime executable. For cacheing Database (SQL) request/reply-pairs, there is memcache. Cacheing HTML output can be done, but is often not a good idea.
See also an earlier answer on a similar question.

Optimizing PHP require_once's for low disk i/o?

Q1)
I'm designing a CMS (-who isn't!) but priority is being given to caching. Literally everything is cached. DB rows, DB id queries, Configuration data, processed data, compiled templates. Currently it has two layers of caching.
The first is a opcode cache or memory cache such as apc, eaccelerator, xcache or memcached. If an entry is not found in there it is then searched for in the secondary slow cache, ie php includes.
Are the opcode caches actually faster than doing a require_once to a php file with a var_export'd array of data in it? My tests are inconclusive as my development box (5.3 of XAMPP) keeps throwing errors installing any of the aforementioned programs.
Q2)
The CMS has numerous helper classes that are autoloaded on demand instead of loading all files. Mostly each has a require before it so no autoloading needs to take place, however this is not the question. Because a page script can have up to 50/60 helper files included I have a feeling that if the site was under pressure it would buckle because of all the i/o that this incurs. Ignore for the moment that there is output cache in place that would remove the need for what I am about to suggest, and also that opcode caches would render this moot. What I have tried to do is join all the helper files required for the scripts execution in one single file. This is achievable and works well, however it has a side effect of greatly increasing the memory usage dramatically even though technically the same code is being used.
What are your thoughts and opinions on this?
Using a compiler cache like APC should help out as it will take your helper files and cache them after they are converted to opcode. That will mean the files will not only be cached but already in opcode so they do not need to be parsed and compiled each time they are required.
Looks like you just have no idea what you want to cache (and why).
You just cannot compare "opcode cache" and "require_once". Opcode cache will cache required code as well as other code.
First, keep in mind that your operating system will cache files in memory if they are being accessed frequently enough.
Also, don't use require_once. It is significantly slower than require. If you aren't using an autoloader, you should be. There is no reason to be manually including files in a modern php application (very few exceptions).
50-60 helper files is crazy. Isn't there some way to combine these? Can't you put them all in a related helper class, like OutputHelper or CacheHelper? That way you only have to include the class, which, again, should be taken care of your autoloader. It sounds to me you're doing something like putting one function per file.
Opcode caching greatly reduces memory usage and execution speed, but I'm not sure what effect it has on require statements.
I agree with ryeguy. require_once is slower than require or include because it has to log every include and check against it. If your only doing one require/include (which you should be for classes) then you don't need require_once or include_once.
Autoloading is great for optimization. As you only will load in classes when needed. So if your app has 500 classes, but only needs 15 to run a certain page/script. Then only those 15 get loaded. Which is nice.
If you take a peak at any big framework. You will notice that they have migrated to using autoloaders. They use to use require_once at the last moment like this example from the Zend Framework Version 1.
require_once 'Zend/Db/Exception.php';
throw new Zend_Db_Exception('Adapter name must be specified in a string');
Zend Framework Version 2 is going to be using auto loaders instead. I believe this is the fastest and it's also the easiest to code for.

Caching always loading files in PHP

In my index.php file I always load some classes used later. From profiler it states it sometimes can take about 20% of entire code. Is there any improvement that can make this process faster?
I would try to make this list of classes shorter, but app is very big and checking all dependencies will be costly.
Op-code caches such as APC and eAccelerator store a compiled version of your scripts in a cache. This dramatically reduces memory usage and loading time for frequently used static scripts.
While using an opcode cache (such as APC) will reduce the impact of loading/parsing/compiling the class, you'll still be loading them all on every page load & doing whatever initialization accompanies a require_once() call. If you were to set up an autoload function then the classes won't be loaded until your code actually needs to use them. There's a little overhead involved in using a class autoloader but it makes the code easier to maintain.
As always, YMMV, so benchmark your application to see if it's worthwhile in your case.
You might want to look at apc php.net/apc

Categories