search
HomeBackend DevelopmentPHP TutorialPHP 开发中的外围资源性能优化分析

首先,后端外围资源,是指跟 PHP 运行过程中与语言本身无关的网络与 IO 操作、存储服务、中间件代理、缓存和数据库访问等,在本文中,我们先分析 IO 操作和中间件服务。

为什么外围资源的性能分析,要以以上三者分析为主?我们可以看如下国内专业的性能监控工具 OneAPM 的 PHP Web 应用后台截取下来的总览图,通过这个图可以看到,数据库所花费的时间在总 PHP 响应时间中,占据着 60% 甚至更大的比重,而 Memcached 缓存服务,在这张图里所占的响应时间,几乎看不见。

一、IO 操作

PHP 语言本身尽管有性能的差异,但是从对 PHP 的性能微观分析也可以看出,如果只执行单次操作,实际中这种差别是非常小的,前面的实验中,十万次以上操作,才有百 ms 级的差别,因为 PHP 语言本身操作的是内存,一次内存访问,大约在 50ns 左右。而 IO 操作,则是磁盘访问,一次磁盘访问所费时间在 5ms 以上。仅从这个数量级看是 10 万倍的差距,实际上,根据实验,也有百倍级的差距(顺序访问和随机访问差距巨大,实际中两者同时进行,还会有磁盘缓存等)。

所以对比语言本身,IO 成为瓶颈的可能性更大。首先看一下,IO 操作带来的性能差别。

一个 PHP 脚本,通过 PHP 命令方式运行,正常时,消耗时间如下:

当使用如下命令清空磁盘缓存后:

echo 3 | sudo tee /proc/sys/vm/drop_caches

代码一模一样,但是运行时间却是正常运行时间的 6 倍。当然这个时间的慢,并不仅仅是由于程序本身的 IO 操作导致,而更大的慢的因素是在 CGI 模式下,PHP 脚本的每一次运行都需要加载所有模块,这个加载,也伴随着大量的 IO 操作。

再做一个实验,完全同样功能的两个页面,一个采用了 MVC 的方式,把头部,尾部拆开成独立的模板(并未使用模板引擎),中间逻辑也使用独立的 Model 类来处理。另一个只 require 了宏定义和数据库操作两个文件。

使用命令ab -c 40 -n 1000 http://xxxxx/0929/zuche/carlist.php 进行压力测试, 这两个页面运行稳定后压测结果数据。

在这个页面中,MVC 版本所费时间要多 6-8ms 左右。虽然只是多增加了几个文件包含,但是明显增加了请求延时,如果文件操作本身更加复杂,比如文件上传、检测、转换,则延时会增加一个数量级以上。在实际的生产使用中,也不是说有了文件操作,就一定会产生大的延时,因为就像本例的 require 而言,由于磁盘缓存等的存在,延时的影响已降低很多。

二、中间件代理

在正式使用中间件之前,我们先对比一下,使用数据库与不使用数据库的差别,同样是上面的这个例子,我们把数据结果集,从数据库获取转换成为直接的结果数组设置,为了结构化清楚,采用 MVC 这一版。同时为了更显著对比上一轮测试结果,同时也消除语言本身的一些慢的因素,在本轮实验中,我们采用 PHP7,得到结果是令人吃惊的。 如下图是带有数据库连接和数据读取的版本,PHP 扩展使用的是 mysqli。

由于本页面,只有一次数据库操作,页面结构也比较简单,语言本身的影响因素非常大,PHP7 下速度有两倍以上提升,原来平均响应时长为 37-40ms,现在则为 14ms。

即使如此,不读取数据库时,有 4ms 的差距,尽管数目上不大,但是对于一个总响应时长只有 14ms 的应用,这 4ms 已经很显著了,而这只是一个数据库查询操作。

接下来看一下,当增加一层数据库中间件时,效率又有怎么样的变化呢?由于笔者所使用的中间件,目前并不支持 PHP7,所以我们还在老版 PHP 的基础上来比对。在同样的服务器压力下,使用了中间件的版本慢了一倍以上。

从这个例子可以看出来,原本 PHP 直接连数据库,取得数据的操作,增加了中间件之后,变了先到中间件,中间件再到数据库,返回亦如是,导致了速度的大幅度下降(这里已经剔除了中间件本身占用资源的因素,在原来直连的版本是 37-40ms 左右)。

这里也请读者不要误解,演示中间件使用速度下降的例子,并不是说为了说明中间件不好,在分布式环境下,使用中间件是非常必要的。而是说,程序的外部资源,往往是影响性能的重要因素,尤其是当外部资源的连接和数据获取本身速度达不到理想的结果时。

对于 IO 操作和中间件服务的分析就到这里,下篇将分析数据库给整个应用性能带来的影响。


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

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

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.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Atom editor mac version download

Atom editor mac version download

The most popular open source editor