Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using too many PHP includes a bad idea?

My question is whether or not using multiple PHP includes() is a bad idea. The only reason I'm asking is because I always hear having too many stylesheets or scripts on a site creates more HTTP requests and slows page loading. I was wondering the same about PHP.

like image 848
NessDan Avatar asked Aug 28 '10 01:08

NessDan


People also ask

How many PHP files do I need?

Each PHP file uses around 10 includes. So for every page that is displayed, the server needs to fetch 10 files, in addition to the rest of its functions (MySQL, etc).

Can we include one PHP file multiple times?

If the file is included twice, PHP will raise a fatal error because the functions were already declared. It is recommended to use include_once instead of checking if the file was already included and conditionally return inside the included file.


2 Answers

The detailed answer:

Every CSS or JS file referenced in a web page is actually fetched over the network by the browser, which involves often 100s of milliseconds or more of network latency. Requests to the same server are (by convention, though not mandated) serialized one or two at a time, so these delays stack up.

PHP include files, on the other hand, are all processed on the server itself. Instead of 100s of milliseconds, the local disk access will be 10s of milliseconds or less, and if cached, will be direct memory accesses which is even faster.

If you use something like http://eaccelerator.net/ or http://php.net/manual/en/book.apc.php then your PHP code will all be precompiled on the server once, and it doesn't even matter if you're including files or dumping them all in one place.

The short answer:

Don't worry about it. 99 times out of 100 with this issue, the benefits of better code organization outweigh the performance increases.

like image 170
dkamins Avatar answered Sep 23 '22 06:09

dkamins


The use of includes helps with code organization, and is no hindrance in itself. If you're loading up a bunch of things you don't need, that will slow things down -- but that's another problem. Clarification: As you include pages, be aware what you're adding to the load; don't carelessly include unneeded resources.

like image 32
Smandoli Avatar answered Sep 19 '22 06:09

Smandoli