On 10/4/2016 4:33 AM, Pascal KISSIAN wrote:
Hi everybody,

I have an application where a small file is included at multiple places.

So far so good.

The problem is that this include consists in a small piece of code which is
inside a multi-level loop.

The include is done about an average of 100.000 times .

When I manually replace the include with the code which is inside, the
performance boost is about  a 50-100 factor..
(with opcache enabled, it is far worst without opcache).

I'm not surprised.

What's wrong with using PHP functions and/or classes? Use 'require_once' outside the loops, which brings in the file containing the function/class, and then execute the function inside the loop. Loading a file repeatedly incurs a lot of processing time to parse it into opcodes, which, as you noticed, the opcode cache helps significantly with. You are also already getting the performance benefits of the file already being in RAM thanks to whatever OS level in-memory file caching system your OS uses. Basically, your code is (ab)using system caching as a performance crutch, which means it is time to refactor your code.

Once you switch to using a function, there are additional techniques that can be used to speed up the function itself - prefer PHP keywords over PHP functions (e.g. array_key_exists() is many times slower than 'isset'), find an alternate algorithm and/or shortcuts with the current algorithm, write a PHP extension, etc.

The 'include' and 'require' keywords invite abuse similar to what you just described and, when abused, will have performance metrics similar to what you described. You aren't the first person to use those keywords in a loop and likely won't be the last. The documentation should be updated to reflect a preference for the 'require_once' and 'include_once' keywords, which would help to avoid the misunderstanding that no one should use any of the code inclusion keywords in a loop.

Personally, I use 'require_once' exclusively for a wide variety of reasons. I've rarely seen a need to use the other include/require keywords. Most of the time I see 'include', I usually think, "That code could be refactored to use 'require_once' and the author would be better off for it."

--
Thomas Hruska
CubicleSoft President

I've got great, time saving software that you will find useful.

http://cubiclesoft.com/

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to