php - 嵌套的 PHP 是否包含 CPU/内存密集型?

标签 php mysql .htaccess include cpu-usage

我正在用 PHP 编写一个站点,并通过将所有请求定向到一个 index.php 文件(使用 .htaccess)来获得“漂亮的 url”(也隐藏了我的目录)。然后索引文件解析 uri 并包含请求的文件。这些文件中还包含多个 include,每个 include 都可以打开一个 MySQL 连接。然后 那些 文件也包含打开 sql 连接的文件。它下降到大约 3-4 个级别。

这个过程是否占用大量 CPU 和内存,无论是来自 PHP 包含还是打开(和关闭)每个包含文件中的 MySQL 连接?

此外,使用纯 htaccess 的漂亮 url 会占用更少的资源吗?

最佳答案

PHP 开销

关于将您的应用程序逻辑分解为源层次结构的答案取决于您的解决方案的托管方式。

  • 如果您使用专用主机/VM,那么您可能会使用 mod_php+Xcache 或 equiv,答案是:不,它不会真正影响运行时间,因为所有内容都在 PHP 操作码级别缓存在内存中。
  • 如果您使用共享托管服务,那么它影响性能,因为任何 PHP 脚本都可能通过 suPHP 通过 PHP-cgi 加载,并且需要读取包含的整个源层次结构并根据请求 编译。更糟糕的是,在共享解决方案中,如果此请求是 1 分钟内的第一个请求,则服务器文件缓存将被刷新并且编码此源将涉及大量物理 I/O = 秒时间延迟。

我管理了几个 phpBB 论坛,发现通过为共享托管实现聚合常见的包含层次结构,我可以将用户响应时间减半。这里有一些文章更详细地描述了这一点(Terry Ellison [phpBB])。并引用一篇文章:

Let me quantify my views with some ballpark figures. I need to emphasise that the figures below are indicative. I have included the benchmarks as attachments to this article, just in case you want to validate them on your own service.

  • 20–40. The number of files that you can open and read per second, if the file system cache is not primed.
  • 1,500–2,500. The number of files that you can open and read per second, if the file system cache is primed with their contents.
  • 300,000–400,000. The number of lines per second that the PHP interpreter can compile.
  • 20,000,000. The number of PHP instructions per second that the PHP interpreter can interpret.
  • 500-1,000. The number of MySQL statements per second that the PHP interpreter can call, if the database cache is primed with your table contents.

有关更多信息,请参阅 More on optimising PHP applications in a Webfusion shared service您可以在其中复制基准以自行运行。

MySQL连接

这里最简单的事情就是将连接池化。我使用我自己的 mysqli 类扩展,它使用标准的类单对象模板。在我的例子中,任何模块都可以发出:

$db = AppDB::get();

返回这个对象。这很便宜,因为它是一个涉及六个 PHP 操作码的内部调用。

另一种但传统的方法是使用全局来保存对象并只做一个

global $db;

在任何需要使用它的函数中。

小型应用的脚注

您建议将所有包含组合到一个包含文件中。这对于稳定生产来说是可以的,但在测试过程中是一个痛苦。我可以建议一个简单的折衷方案吗?将它们分开进行测试,但允许加载单个复合 Material 。您分两部分执行此操作 (i) 我假设每个包含定义一个函数或类,因此为每个包含使用标准模板,例如

if( !function_exists( 'fred' ) ) {
    require "include/module1.php";
}

在主脚本中的任何加载之前简单地做:

@include "include/_all_modules.php";

这样,当您进行测试时,您删除 _all_modules.php 并且脚本回退到加载单个模块。当您满意时,您可以重新创建 _all_modules.php。您可以通过一个简单的“发布”脚本来完成此服务器端的事件,该脚本执行一个

system( 'cp include/[a-z]*.php include/_all_modules.php' );

这样一来,你就能两全其美

关于php - 嵌套的 PHP 是否包含 CPU/内存密集型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9274634/

相关文章:

php - 你会如何处理这个 php/mysql

php - 添加多个规范而不先保存

java - Spring中未加载Bean方法 'dataSource'

.htaccess - 发送多个值时 RewriteRule 不起作用

.htaccess - Magento 1.9 - 重定向太多

php - 使用 foreach 循环比较两个数组

PHP将登录文件加载到div中而不重新加载url

javascript - kcfinder 空白浏览页面

php - Facebook 第二次验证用户身份

regex - Apache mod_rewrite 正则表达式限制匹配最大量词?