Can you put too much information into a variable? - php

I'm creating a script that makes use of the $GLOBALS variable quite a lot. Is there too much you can put into a variable?
If I have a lot of information stored in $GLOBAL variable when the page loads, is this going to slow down the site much or not really?
Is there a limit to how much information one should store in a variable? How does it work?
And would it be better to remove information from that variable when I am done with it?
Thanks for your help! Want to make sure i get this right before I go any further.

In PHP, there's a memory_limit configuration directive (in php.ini) that you should be aware of.
As meder says, you should really be taking a step back and re-evaluating things. Do you actually use all of those data on each and every web server request.
In almost every case, you'd be better off loading only the data you need, when you need it.
For instance, even if you're reading all this data from some file, instead of a database, you're probably better off splitting that file up into logical groups, and loading the data you need (once!), just before using it (the first time).
Assuming you're running Apache/mod_php, loading everything on every request will balloon the size of your httpd processes, and when you scale with traffic, you'll just start swapping out (which means your app will slow to a crawl, or even worse, become deadlocked) that much faster.
I you really need all or most of the data available for all (or nearly all) requests, consider looking into something like memcache. You can devise ways to share (read-only) data between processes, instead of duplicating it for each and every request.

Some people use a "Registry" object to handle globals.
See how Kevin Waterson does it:
http://www.phpro.org/tutorials/Model-View-Controller-MVC.html (See "5. The Registry")

Related

PHP - Using Sessions to temporarily save variables for ajax application

I wonder if the following would be a good Idea or rather contra-productive performance-wise:
An Ajax-Application, like for example a pagebrowser needs some language- and config-values, which are stored in the database. So each time, the user is using this app, in the ajax-script the mysql-query to get the variables is done again and again. concidering this for a pagebrowser, there might be like 10 or more requests (back and forward, back, forward, and so on), aka 10 x database-select, while it is needed only one time actually.
My idea was, to safe the config-vars in a session-array the first time, the ajax-app is requested. If the sessions-array exists, the mysql-query isnt done again.
if the user calls another regular page, these session-array is deleted again.
Now im not really sure, what would consume more server-resources, using sessions in the above described way for saving the vars teporarily, or just using a mysql-query to get the vars each time, the user klicks the ajax-app.
Thanx in advance, Jayden
If you working with massive amount of data, you could consider using Cookies as well instead of session for server resources, which will be stored in the user's local browser.
I'd bet sessions would be more effective, but the best way is to test and measure the different execution times.

Performance impact when require-ing a file many times vs reusing it

Think of PHP templating.
I was recently contemplating whether it makes sense to read a template file once, storing it in memory, and then parsing it (replace placeholders with values, e.g.) rather than require-ing that file as many times as you need it. A usage scenario would be a list with list items templated as separate files. The first thoughts I had were inclined towards the former solution, because I reckon replacing values would be an easier operation than requiring the file from the file system. Later, however, I realized that pretty much all hard disk drives (or other storage, for that matter) have their own caching, and requiring the same file over and over, will not result in it being re-read each time, but rather re-served from the cache.
Any thoughts are appreciated.
I assume by "disk cache" you're actually referring to the page cache? Wikipedia: Page Cache
If so I wouldn't really be inclined to trust something like this with the performance of my application. Don't forget the page cache only uses UNUSED memory and will happily spit it back out when needed.
I would be inclined to use something like APC as an object cache, this has the great side effect of not having to actually rewrite any of your code as it's all done behind the scenes. Another possibility would be to just assign your template to a variable and constantly reuse that. Or, if you wanted to you could even use Memcache, this kind of stuff is more useful for caching database returns though, or large datasets.
Sorry for the slightly incoherent ramblings...
I was recently contemplating
That's quite wrong of you.
Groundless contemplating out of nowhere seldom does any good but most likely will put you in a trouble. Just out of nowhere.
Instead of contemplating, one have to do profiling.
Of course no to measure any changes, like H Hatfeld said, but to determine, if they need any changes at all. Most of time it turns out that you were barking wrong tree.
Profiling is the right thing to make you bark the right one.
whether it makes sense to read a template file onc, estoring it in memory, and then parsing it
For the highload(or bloated) projects it makes.
So, PHP already have such a feature, called bytecode cache. There is a plenty of the thing on the market, at our company we are using eAccelerator.
But most of time default every-request parsing is enough.
You are absolutely right about filesystem cache and parsing being blazingly fast, much faster than usual application logic, which has to be optimized at the first place.
Every time you include a file, PHP has to parse it. This penalty can be offset using an opcode cache like APC. If your templates don't contain any PHP (which it sounds like they don't), I would recommend loading the template into memory once and then re-using it as needed.
Another thing to keep in mind when looking to optimize your code is make sure you can measure the change. Use something like Xdebug to profile your code and measure what effect your changes are having.
Edit
Since the files do currently contain PHP, take a look at this question/answer. I would recommend putting a function in the file so that it only needs to be loaded once, but can be called multiple times with different parameters.

Efficiency of using php to load scripts?

I have a website that's about 10-12 pages strong, using jQuery/Javascript throughout. Since not all scripts are necessary in each and every page, I'm currently using a switchstatement to output only the needed JS on any given page, so as to reduce the number of requests.
My question is, how efficient is that, performance-wise ? If it is not, is there any other way to selectively load only the needed JS on a page ?
This may not be necessary at all.
Bear in mind that if your caching is properly set up, embedding a JavaScript will take time only on first load - every subsequent request will come from the cache.
Unless you have big exceptions (like, a specific page using a huge JS library), I would consider embedding everything at all times, maybe using minification so everything is in one small file.
I don't see any performance issues with the method you are using, though. After all, it's about deciding whether to output a line of code or not. Use whichever method is most readable and maintainable in the long term.
Since you're using JS already, you can use JS solution completely - for example you could use yepnope instead of php. I don't know what's the structure of your website and how you determine which page needs what or at what point is something included (on load, on after some remote thing has finished delivering data), however if you use $.ajax extensively, you could also use yepnope to pull additional JS that's needed once $.ajax is done with what it was supposed to do.
You can safely assume the javascript is properly cached on the clientside.
As I also assume you serve a minified file, seen the size of your website I'd say the performance is neglectable.
It is much better to place ALL your JavaScript in a single separate ".js" file and reference this file in your pages.
The reason is that the browser will cache this file efficiently and it will only be downloaded once per session (or less!).
The only downside is you need to "refresh" a couple of times if you change your script.
So, after tinkering a bit, I decided to give LABjs a try. It does work well, and my code is much less bloated as a result. No noticeable increase in performance given the size of my site, but the code is much, much more maintainable now.
Funny thing is, I had a facebook like button in my header. After analyzing the requests in firebug I decided to remove it, and gained an astounding 2 seconds on the pages loading time. Holy crap is this damn thing inneficient...
Thanks for the answers all !

Tricks to speed up page load time in PHP

I know of these two tricks for speeding page load time up some:
#ini_set('zlib.output_compression', 1);
which turns on compression
ob_implicit_flush(true);
which implicitly flushes the output buffer, meaning as soon as anything is output it is immediately sent to the user's browser. This one's a tad tricky, since it just creates the illusion that the page is loading quickly while in actuality it takes the same amount of time and the data is just being shown faster.
What other php tricks are there to make your pages load (or appear to load) faster?
It is always better to define a real bottleneck and then try to avoid it.
The way to follow any trick that is supposed to make something faster without understanding whether you have the problem or not - is always a wrong way.
The best way is to ensure that your script isn't creating/destroying unnecessary variables and make everything as efficient as possible. After that, you can look into a caching service so that the server does not have to reparse specific parts of a page.
If all that doesn't make it as fast as you need it to be, you can even "compile" the php code. Facebook does this to support faster load times. They created something called "HipHop for PHP" and you can read about it at: https://developers.facebook.com/blog/post/358/
There are other PHP compilers you can use to help.
If all this fails, then I suggest you either recode the website in a different language, or figure out why it is taking so long (more specifically, WHAT is causing it to take so long) and change that part of the website.
There are some that can speed your website(code custmoization)
1) If you’re looping through an array, for example, count() it beforehand, store the value in a variable, and use that for your test. This way, you avoid needlessly firing the test function with every loop iteration.
2) use build in function instead of custom function
3) put JavaScript function and files at bottom of file
4) use caching
Among the best tricks to speed up PHP page loads is to use as little PHP as possible, i.e. use a PHP cache/accelerator such as Zend or APC, or cache as much as you can yourself. PHP that does not need to be parsed again is faster, and PHP that does not run at all is still faster.
The same goes (maybe even more so) for database. Use as few queries as possible. If you can combine two queries into one, you save one round trip.

Is there a variable scope that is accessible anywhere in PHP?

I'd like to create something like a very basic chat application. I don't want to use a database, since it'd cause a heavy load on an already strained db. I also don't want to use a flat file, because it have a feeling that it'd become a mess or that it'll have lots of read/writes...
So, I'm wondering if there is a way to have a variable that is accessible in any file and at any time.
Well if you don't want a file, you're left with shared memory.
You could try PHP's shared memory functions, or use an extension like memcache or APC.
You can't share variable values among separate requests - think of each request like the entire program is starting and finishing each time, even if there are several requests happening at once.
You could look into storing data in a cache layer (for example, memcached) however it sounds like you need to cache your database if it's under heavy load. I'd recommend caching your database (again memcached or file-based storage; serialize() data first) and then when that problem is solved store the chat data in the database (which is in turn cached). You need to store it persistently somewhere.
There isn't such thing. Try creating a basic file that saves serialized/json'd version of the variable you want, use php's flock to manage access to that file, cycle the file every hour/day. Since it's no big traffic simple app, I think this will be okay.

Categories