search
HomeBackend DevelopmentPHP TutorialPHP data caching technology three_PHP tutorial

PHP data caching technology three_PHP tutorial

Jul 15, 2016 pm 01:23 PM
phpoptimizationusebenefitstudyappperformancetechnologydatayesmaximumofcacheprogrammingprogramming language

PHP应用程序的性能优化
使用PHP编程的最大好处是学习这种编程语言非常容易以及其丰富的库。即使对需要使用的函数不是十分了解,我们也能够猜测出如何完成一个特定的任务。
尽管PHP非常简单易学,但我们仍然需要花费一点时间来学习PHP的一些编程技巧,尤其是与性能和内存占用相关的技巧。在PHP中,有许多小技巧能够使我们减少内存的占用,并提高应用程序的性能。在本篇文章中,我们将对PHP应用程序的分析、如何改变脚本代码以及比较优化前后的各种参数值进行简要的介绍。

通过在程序中设置计时的程序,并反复执行这些代码,我们可以获得有关程序执行速度的一组数据,这些数据可以可以用来发现程序中的瓶颈,以及如何进行优化,提高应用程序的性能。

也许读者曾经听说过PEAR库吧。我们将使用PEAR库创建在分析时需要使用的例子,这也是对现有的代码进行分析的最简单的方法,它使我们无需使用商用产品就能对代码进行分析。
我们要使用的库的名字是PEAR::Benchmark,它对于对代码进行分析和性能测试非常有用。这个库提供一个名字为Benchmark_Timer()的类,能够记录一个函数调用和下一个函数调用之间的时间。在对代码的性能进行测试时,我们可以得到一个详细的脚本执行结果,它非常简单,如下所示:

include_once("Benchmark/Timer.php");<br>$bench = new Benchmark_Timer;<br>$bench-> start();<br>$bench-> setMarker('Start of the script');<br>// 现在处于睡眠状态几分钟<br>sleep(5);<br>$bench-> stop();<br>// 从计时器中获得分析信息<br>print_r($bench-> getProfiling());<br>?>   <br>上面代码执行后的输出如下所示: <br>Array<br>(<br>[0] =>  Array<br>(<br>[name] =>  Start<br>[time] =>  1013214253.05751200<br>[diff] =>  -<br>[total] =>  0<br>)<br>[1] =>  Array<br>(<br>[name] =>  Start of the script<br>[time] =>  1013214253.05761100<br>[diff] =>  9.8943710327148E-05<br>[total] =>  9.8943710327148E-05<br>)<br>[2] =>  Array<br>(<br>[name] =>  Stop<br>[time] =>  1013214258.04920700<br>[diff] =>  4.9915959835052<br>[total] =>  4.9916949272156<br>)<br>)

上面的数字似乎是一组杂乱无章的数字,但如果程序的规模更大,这些数字就十分地有用了。
也许广大读者也能猜测到,数组的第一个表目是实际调用Benchmark_Timer()类的方法,例如
$bench-> start()、$bench-> setMarker()和$bench-> stop(),与这些表目有关的数字是相当简单的,现在我们来仔细地研究这些数字:
[0] =>  Array <br>( <br>[name] =>  Start <br>[time] =>  1013214253.05751200 <br>[diff] =>  - <br>[total] =>  0 <br>)

time表目指的是何时对Benchmark_Timer()的start()方法调用的UNIX的timestamp,diff表目表示这次调用和上次调用之间的时间间隔,由于这里没有上一次,因此显示出了一个破折号,total表目指的是自测试开始到这一特定的调用之前代码运行的总的时间。下面我们来看看下一个数组的输出:
[1] =>  Array <br>( <br>[name] =>  Start of the script <br>[time] =>  1013214253.05761100 <br>[diff] =>  9.8943710327148E-05 <br>[total] =>  9.8943710327148E-05 <br>) 

从上面的数字我们可以看出,在调用$bench-> start()之后,程序运行了9.8943710327148E-05秒(也就是0.0000989秒)后开始调用$bench-> setMarker(....)。

一次真实的性能测试经历
尽管上面的例子不错,但在对于决定如何优化你的站点代码设计方面,它真的不能算是一个好例子。下面我将用我自己作为网站技术人员的一段亲身经历来说明如何解决性能方面存在的问题。
我并不大理解网站使用的代码,因为它是根据特殊的需求,历经多年开发而成的━━其中的一个模块包括网站转换代码,另一个模块记录网站的使用情况,其他的模块也各有各的作用。我和网站的主要开发者都意识到网站的代码需要优化,但又不清楚问题出在哪儿。
为了尽快地完成任务,我开始研究网站的主要脚本代码,并在全部脚本代码以及其包含文件中添加了一些$bench-> setMarker()命令,然后分析$bench-> getProfiling()的输出,并对得到的结果大吃一惊,原来问题出在一个与获得特定语言名字(例如en代表english)的转换代码的函数调用中,该函数在每个页面上都会被使用数百次。每次调用该函数时,脚本代码都会对一个MySQL数据库进行查询,从一个数据库表中获得真正的语言名字。
于是我们这一类的信息创建了一个缓冲系统。经过短短2天时间的工作,我们使系统的性能得到了很大的提高,第一周内页面的浏览量也因此而增加了40%。当然了,这只是一个有关分析代码能够提高互联网应用或互联网网站性能的例子。
性能测试函数调用
在分析一个脚本或网页(以及其包含文件)时,尽管Benchmark_Timer()特别有用,但它并不科学,因为要获得分析的数据我们必须多次加载脚本,而且它也不是针对某个类或函数调用的。
PEAR::Benchmark库中的另一个被称作Benchmark_Iterator的类能够很好地解决这一个问题,它能够针对特定的函数或类的方法,显示其分析信息。它的用途是能够能够从测试中获得一致的结果,因为我们知道,如果运行一段脚本一次,其运行时间为10秒,并不意味着它每次的运行时间总是10秒。

In any case, let's see some examples: <br>// 连接数据库的代码<br>include_once("DB.php");<br>$dsn = array(<br>'phptype' =>  'mysql',<br>'hostspec' =>  'localhost',<br>'database' =>  'database_name',<br>'username' =>  'user_name',<br>'password' =>  'password'<br>);<br>$dbh = DB::connect($dsn);<br>function getCreatedDate($id)<br>{<br>global $dbh;<br>> $stmt = "SELECT created_date FROM users WHERE id=$id";<br>// 在这里使用PEAR::DB<br>$created_date = $dbh-> getOne($stmt);<br>if ((PEAR::isError($created_date)) || <br>(empty($created_date))) {<br>return false;<br>} else {<br>return $created_date;<br>}<br>}<br>include_once 'Benchmark/Iterate.php';<br>$bench = new Benchmark_Iterate;<br>// 运行getDate函数10次<br>$bench-> run(10, 'getCreatedDate', 1);<br>// 打印分析信息<br>print_r($bench-> get());<br>?> 
运行上面的代码能够产生与下面相似的结果:
Array<br>(<br>[1] =>  0.055413007736206<br>[2] =>  0.0012860298156738<br>[3] =>  0.0010279417037964<br>[4] =>  0.00093603134155273<br>[5] =>  0.00094103813171387<br>[6] =>  0.00092899799346924<br>[7] =>  0.0010659694671631<br>[8] =>  0.00096404552459717<br>[9] =>  0.0010690689086914<br>[10] =>  0.00093603134155273<br>[mean] =>  0.0064568161964417<br>[iterations] =>  10<br>)

上面的这些数字很好理解,mean条目表示getCreatedDate()函数10次运行的平均时间。在进行实际测试时,应该至少运行1000次,但这个例子得出的结果已经足够说明问题了。 (责任编辑:

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/446852.htmlTechArticlePHP应用程序的性能优化 使用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
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

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

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

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

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.