开发者

Efficiency for including files of functions (in PHP)

开发者 https://www.devze.com 2022-12-17 20:33 出处:网络
If I had a large number of functions would it be better to keep them all in one large file or would it be better to separate them into several files of related functions. By better I mean more efficie

If I had a large number of functions would it be better to keep them all in one large file or would it be better to separate them into several files of related functions. By better I mean more efficient for both maintainability and for the server processing the request.

For example right now I have all my files in a file named include.php. But would it be wiser to have an include file of includes like:

<?php
 include('/functions/user.php');
 include('/functions/admin.php');
 include('/functions/content.php');
 include('/functions/nav.php');
 include('/functions/database.php');
 include('/f开发者_开发问答unctions/other_junk.php');
?>


Definitely separate them, for maintainability sake. I doubt performance will suffer at all, but even if it does (just a teensy bit) you're better off writing maintainable, readable code.


You want to be sure you're using a PHP cache like XCache or APC. Your PHP files should then all be in memory and you shouldn't be worried about your includes hitting the disk at all.

I would definitely find it easier if you broke up like minded functions/classes into their own files.


In terms of maintainability, it's usually better to separate your functions into related groups. ( like you showed above, user.php would be only the user-related functions ).

You should only have a file that has all of those includes if you know that you'll need all of the included files every time you need to include any file. Otherwise, it defeats the purpose of having that 'catch-all' file.


In my experience multiple includes and/or requires generally arent goping to set you too much back if youre talking a couple dozen or so files for function libraries. Especially if you can manage to only call the statement for a particular file once during a request lifecycle.

Where it starts to show performance hits is if you get into OOP or a highly complex functional/procedural type architecture where there may be hundreds of different classes/files. But generally at that point youll have hopefully done some kind of mitigation via caching/compiling.


I have a list of includes in a central .config file.

For all OOP classes though I use autoload -> I know it's slightly slower, but it saves having to including them as I make a new class. And they're only loaded as required.

As an aside, include is quicker than include_once as it doesn't have to check if the file has been included already.

0

精彩评论

暂无评论...
验证码 换一张
取 消