If, else if, else using alot of memory? what is happening?


I am trying to cut back on my memory usage and found a php function called (memory_get_usage), which I used and printed off on the footer of my page. I was experimenting on a large page with something like this:

if (var == 1) {
//section 1 code...
else if (var == 2) {
//section 2 code...
else {
//section 3 code...

Well, I started with var = 1 and I deleted everything (section 2 code block) inside the brackets for var = 2. It turns out that memory_get_usage() showed that a lot of memory was cut from usage when I did this. If I put section 2 back in, the memory goes back up, even though the script SHOULD, as far as I know, ignore everything inside the brackets! I would like the server to just ignore everything in the brackets that I’m not using.

So I was wondering if someone could please explain this and what I can do to cut back on memory in this case.


The server reads your PHP files and compiles the code into an executable format in memory. Even if that conditional code doesn’t execute, it is still compiled and is in memory.

If memory consumption is your problem, and judging from your other thread it appears to be, in the conditional section take out the code, put it in a separate file, and include that file only if the section two block executes.

Thanks for the reply cheesedude,

So if I put each section block of code into an include file, wont that also compile into an executable format in memory or be used for memory allocation?

When developing I use this all the time and it drastically improves LOCALHOST rendering:

# config file
 defined('LOCALHOST') ? NULL : define('LOCALHOST', in_array($_SERVER['SERVER_NAME'], array('localhost', '') ));

# footer
<?php if( ! LOCALHOST ) { include PATH_ADVERTS .'_analytics.js';} ?>


Thanks for the responses, this seems to have helped knock off about a quarter megabyte off of each page load. There is another issues though. I found another php function: memory_get_peak_usage() and according to the php manual, this is how much memory is allocated. I’m guessing that this is the important number that should be reduced in order to conserve memory.

On a few of my pages, I am able to drop the memory usage down by 200 kilobytes by converting blocks of codes into include files. The problem is that the memory_get_peak_usage() number barely decreases at all.

Here are what my numbers look like when I display them in the footer:
memory_get_peak_usage() - 745792
memory_get_usage() - 331048

Let me know what might be happening here.