search

php代码执行效率

这里说一些代码的执行情况,虽然php执行起来很快,但是蚊子虽小,总还是肉吧~

?

下面是一些代码的执行时间。

?

//以下程式执行次数$_i =1000000;
?

下面我们来看下for循环

?

/** * 这就是以前经常写的循环和判断 * for(i=0;i<p>?<span style="font-size: medium;">同样是循环($_i)次,而下面的却比上面的少花费0.01~0.02秒。原因是每次不用去判断$_i,因为当$_i=0的时后,判断就为false了。</span></p><p>?</p><p><span style="font-size: medium;">所以我们的if判断也可以这样写</span></p><pre name="code" class="java">$_val = 1;if ($_val) {}

?只要是数字都是ture,0就是false啦


下面这个是很容易犯的错误,在循环中声明变量,我们来看下执行时间

$_val = 1;for($_i;$_i;$_i--){	if ($_val) {		}}/** * 执行时间 * 0.100801944733 * 0.0974791049957 * 0.0993800163269 * 0.112987041473 *///把变量放在循环中for($_i;$_i;$_i--){	$_val = 1;	if ($_val) {	}}/** * 执行时间 * 0.133583068848 * 0.117377996445 * 0.116209983826 * 0.12203502655 */

?上面的代码可以看出差距了吧


判断或者的情况

$_val = 3;for($_i;$_i;$_i--) {	if (3 == $_val || 4 == $_val || 5 == $_val) {	}}/** * 执行时间 * 0.11983704567 * 0.12117600441 * 0.129379987717 * 0.131067991257 */$_val = 5;for($_i;$_i;$_i--) {	if (3 == $_val || 4 == $_val || 5 == $_val) {	}}/** * 执行时间 * 0.27806186676 * 0.316290855408 * 0.259559869766 * 0.277565956116 *///用php自带的函数$_val = 5;for($_i;$_i;$_i--) {	if (in_array($_val,array(3,4,5))) {	}}/** * 1.13307905197 * 1.12578582764 * 1.14648389816 */

?有php函数就用php函数吧,你会发现php函数简单好用。


还有一个查询的

//比如查詢統計的時候,查看該會員某些條件下是否有po過文章SELECT id FROM post WHRE user_id='{$_user_id}' AND ......//這樣寫沒錯啦,就是效率很慢,其實就是查詢是否有該數據,可以在後面添加一限制條數  LIMIT 1SELECT id FROM post WHRE user_id='{$_user_id}' AND ...... LIMIT 1
?

希望以上写的对大家有所帮助。

?

1 楼 liuzhiqiangruc 2011-07-02  
哥那个或者的例子第一个快是因为比较到3的时候后两个比较不用做来了。而用in_array的问题在于每次循环要构造一个array(3,4,5),构造一个array是比较费事的。还有为啥要在循环里面构造array,在循环外够在array不是更快吗?


此外,最后一个查询的例子,加不加limit 1取决于业务需求吧,如果只要查得一条记录,加上当然没问题。

2 楼 wangyangtoy 2011-07-06  
liuzhiqiangruc 写道
哥那个或者的例子第一个快是因为比较到3的时候后两个比较不用做来了。而用in_array的问题在于每次循环要构造一个array(3,4,5),构造一个array是比较费事的。还有为啥要在循环里面构造array,在循环外够在array不是更快吗?


此外,最后一个查询的例子,加不加limit 1取决于业务需求吧,如果只要查得一条记录,加上当然没问题。

我举的例子,就是说明如果用“||"的话是要看运气的,而用in_array用的速度都一样哦~
你说的构造一个array(3,4,5),你说的对,可以把它拿到循环外面,这个我上面也有说明
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!

EditPlus Chinese cracked version

EditPlus Chinese cracked version

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

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft