PHP: Equivalent of include using eval

后端 未结 8 1258
清酒与你
清酒与你 2020-12-06 05:56

If the code is the same, there appears to be a difference between:

include \'external.php\';

and

eval(\'?>\' . file_get_conten

8条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-06 06:12

    Some thoughts about the solutions above:

    Temporary file

    Don't. It's very bad for performance, just don't do it. Not only does it drive your opcode cache totally crazy (cache hit never happens + it tries to cache it again every time) but also gives you the headache of filesystem locking under high (even moderate) loads, as you have to write the file and Apache/PHP has to read it.

    Simple eval()

    Acceptable in rare cases; don't do it too often. Indeed it's not cached (poor opcode cache just doesn't know it's the same string as before); at the same time, if your code is changing each time, eval is A LOT BETTER than include(), mostly because include() fills up the opcode cache on each call. Just like the tempfile case. It's horrible (~4x slower).

    In-memory eval()

    Actually, eval is very fast when your script is already in the string; most of the time it's the disk operation that pulls it back, now surely this depends on what you do in the script but in my very-small-script case, it was ~400 times faster. (Do you have memcached? Just thinking loud) So what include() can't do is evaluate the same thing twice without file operation, and this is very important. If you use it for ever-changing, small, memory-generated strings, obviously it's eval to choose - it's many-many times faster to load once + eval again and again than an iterated include().

    TL;DR

    • Same code, once per request: include
    • Same code, several calls per request: eval
    • Varying code: eval

提交回复
热议问题