search

作者: Laruence本文地址: http://www.laruence.com/2011/02/13/1870.html 转载请注明出处

你也许注意到过, 在PHP中使用ECHO输出大段字符串的时候, 执行时间会明显的长, 也就会有朋友认为PHP的ECHO性能很差.

我在之前的文章中, 已经解释过了原因, 也希望能纠正”PHP的ECHO性能差”的这个误会.

然而之前的文章, 也仅仅是给出了原因, 并没有介绍如何避免这个问题, 在今天公司内的某个产品线(Apache with PHP)发现了一个问题, 有用户在短时间内大量发起下载请求, 导致http连接数和数据库连接数剧增,

而数据库连接数剧增的原因是因为数据库的连接是单列模式, 一直到请求处理结束, 才会释放数据库链接. 这样就有了一个问题, 如果请求处理时间过长, 就会造成大量的数据库链接存在.

而这个用户的网速很慢, 这也就意味着, ECHO的”性能”很差~, 下载时间很长~. 如下图所示:

ECHO执行示意图

这也就引出了今天我要谈的这个问题, 如何让ECHO变快, 让PHP的请求处理过程, 尽快结束…

我们知道, 之所以ECHO慢, 是在等待”写数据”成功返回, 那么一个比较简单的办法, 就是打开输出缓存,

编辑php.ini

 output_buffering = 4096 //byte

当然, 你也可以在脚本中, 显示的调用ob_start():

ob_start(); echo $huge_string; //其他的逻辑. ob_end_flush();

这里, 有一个要注意的地方, ob_start将会开辟一块4096大小的buffer, 所以, 如果huge_string大于4096, 将不会起到加速的作用.

现在, 我们的ECHO就会”立即”执行成功, 返回. 因为数据暂时写到了我们的输出缓存当中. 如果buffer足够大, 那么内容会等到脚本的最后, 才一次性发送给客户端(严格来说, 是发送给WebServer).

但这样并不能解决我们今天遇到的这个问题, 因为这些数据到最后, 还是需要PHP去把它们发送给客户端(此时不考虑WebServer的Output buffer), 这个过程不结束, 请求不会关闭, PHP也不会执行DB的析构函数~

那么, 既然做梦, 那就再做大点, 我们可以使用Apache的输出缓存. 也就是改变成如下的执行流程:

加速ECHO示意图

假设, 我们的PHP要输出100K的数据, 那么, 我们Apache的的输出缓存就必须大于100K, 否则当Apache的输出缓存满了以后, 就会真正的发送给客户端, 而这个过程中, 当时执行的ECHO就会阻塞等待.

那么, 如何修改Apache的输出缓存呢? 我们可以在apache的配置文件中, 使用SendBufferSize配置指令:

    SendBufferSize 4096 //注意是byt

具体的SendBufferSize的说明, 参看http://httpd.apache.org/docs/2.0/en/mod/mpm_common.html#sendbuffersize

注: 其他的Webserver with php-cgi的模式, 请翻阅相关Webserver的手册, 寻找类似配置.

现在, PHP的ECHO, 将直接把内容交给Apache, PHP在执行完成后, 不再等待内容发送给客户端完成, 而直接退出. 而内容会在PHP处理完成以后, 由Apache发送给客户端. 从而加速了ECHO的执行效率.

废话一句: printf, print, file_put_contents(“php://output”)…等等, 和ECHO都是一样的.

最后要说明, 这样做, 只是把原来ECHO的等待时间, 转移给了Apache, 并没有真正的减少客户端获取到内容的时间. 它只是加速了PHP的处理过程, 提前了PHP的退出时机, 从而能减少PHP对资源的占用时间, 间接增加资源的占用率.

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

Simple Guide: Sending Email with PHP ScriptSimple Guide: Sending Email with PHP ScriptMay 12, 2025 am 12:02 AM

PHPisusedforsendingemailsduetoitsbuilt-inmail()functionandsupportivelibrarieslikePHPMailerandSwiftMailer.1)Usethemail()functionforbasicemails,butithaslimitations.2)EmployPHPMailerforadvancedfeatureslikeHTMLemailsandattachments.3)Improvedeliverability

PHP Performance: Identifying and Fixing BottlenecksPHP Performance: Identifying and Fixing BottlenecksMay 11, 2025 am 12:13 AM

PHP performance bottlenecks can be solved through the following steps: 1) Use Xdebug or Blackfire for performance analysis to find out the problem; 2) Optimize database queries and use caches, such as APCu; 3) Use efficient functions such as array_filter to optimize array operations; 4) Configure OPcache for bytecode cache; 5) Optimize the front-end, such as reducing HTTP requests and optimizing pictures; 6) Continuously monitor and optimize performance. Through these methods, the performance of PHP applications can be significantly improved.

Dependency Injection for PHP: a quick summaryDependency Injection for PHP: a quick summaryMay 11, 2025 am 12:09 AM

DependencyInjection(DI)inPHPisadesignpatternthatmanagesandreducesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itallowspassingdependencieslikedatabaseconnectionstoclassesasparameters,facilitatingeasiertestingandscalability.

Increase PHP Performance: Caching Strategies & TechniquesIncrease PHP Performance: Caching Strategies & TechniquesMay 11, 2025 am 12:08 AM

CachingimprovesPHPperformancebystoringresultsofcomputationsorqueriesforquickretrieval,reducingserverloadandenhancingresponsetimes.Effectivestrategiesinclude:1)Opcodecaching,whichstorescompiledPHPscriptsinmemorytoskipcompilation;2)DatacachingusingMemc

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft