優化PHP代碼的40條建議(轉)

優化PHP代碼的40條建議 40 Tips for optimizing your php Code 原文地址:http://reinholdweber.com/?p=3 英文版權歸Reinhold Weber所有,中譯文作者yangyang(aka davidkoree)。雙語版可用于非商業傳播,但須注明英文版作者、版權信息,以及中譯文作者。翻譯水平有限,請廣大PHPer指正。

1. If a method can be static, declare it static. Speed improvement is by a factor of 4. 如果一個方法可靜態化,就對它做靜態聲明。速率可提升至4倍。

2. echo is faster than print. echo 比 print 快。

3. Use echo’s multiple parameters instead of string concatenation. 使用echo的多重參數(譯注:指用逗號而不是句點)代替字符串連接。

4. Set the maxvalue for your for-loops before and not in the loop. 在執行for循環之前確定最大循環數,不要每循環一次都計算最大值。

5. Unset your variables to free memory, especially large arrays. 注銷那些不用的變量尤其是大數組,以便釋放內存。

6. Avoid magic like __get, __set, __autoload 盡量避免使用__get,__set,__autoload。

7. require_once() is expensive require_once()代價昂貴。

8. Use full paths in includes and requires, less time spent on resolving the OS paths. 在包含文件時使用完整路徑,解析操作系統路徑所需的時間會更少。

9. If you need to find out the time when the script started executing, $_SERVER[’REQUEST_TIME’] is preferred to time() 如果你想知道腳本開始執行(譯注:即服務器端收到客戶端請求)的時刻,使用$_SERVER[‘REQUEST_TIME’]要好于time()。

10. See if you can use strncasecmp, strpbrk and stripos instead of regex. 檢查是否能用strncasecmp,strpbrk,stripos函數代替正則表達式完成相同功能。

11. str_replace is faster than preg_replace, but strtr is faster than str_replace by a factor of 4. str_replace函數比preg_replace函數快,但strtr函數的效率是str_replace函數的四倍。

12. If the function, such as string replacement function, accepts both arrays and single characters as arguments, and if your argument list is not too long, consider writing a few redundant replacement statements, passing one character at a time, instead of one line of code that accepts arrays as search and replace arguments. 如果一個字符串替換函數,可接受數組或字符作為參數,并且參數長度不太長,那么可以考慮額外寫一段替換代碼,使得每次傳遞參數是一個字符,而不是只寫一行代碼接受數組作為查詢和替換的參數。

13. It’s better to use select statements than multi if, else if, statements. 使用選擇分支語句(譯注:即switch case)好于使用多個if,else if語句。

14. Error suppression with @ is very slow. 用@屏蔽錯誤消息的做法非常低效。

15. Turn on apache’s mod_deflate 打開apache的mod_deflate模塊。

16. Close your database connections when you’re done with them. 數據庫連接當使用完畢時應關掉。

17. $row[’id’] is 7 times faster than $row[id]. $row[‘id’]的效率是$row[id]的7倍。

18. Error messages are expensive. 錯誤消息代價昂貴。

19. Do not use functions inside of for loop, such as for ($x=0; $x < count($array); $x) The count() function gets called each time. 盡量不要在for循環中使用函數,比如for ($x=0; $x < count($array); $x)每循環一次都會調用count()函數。

20. Incrementing a local variable in a method is the fastest. Nearly the same as calling a local variable in a function. 在方法中遞增局部變量,速度是最快的。幾乎與在函數中調用局部變量的速度相當。

21. Incrementing a global variable is 2 times slow than a local var. 遞增一個全局變量要比遞增一個局部變量慢2倍。

22. Incrementing an object property (eg. $this->prop++) is 3 times slower than a local variable. 遞增一個對象屬性(如:$this->prop++)要比遞增一個局部變量慢3倍。

23. Incrementing an undefined local variable is 9-10 times slower than a pre-initialized one. 遞增一個未預定義的局部變量要比遞增一個預定義的局部變量慢9至10倍。

24. Just declaring a global variable without using it in a function also slows things down (by about the same amount as incrementing a local var). PHP probably does a check to see if the global exists. 僅定義一個局部變量而沒在函數中調用它,同樣會減慢速度(其程度相當于遞增一個局部變量)。PHP大概會檢查看是否存在全局變量。

25. Method invocation appears to be independent of the number of methods defined in the class because I added 10 more methods to the test class (before and after the test method) with no change in performance. 方法調用看來與類中定義的方法的數量無關,因為我(在測試方法之前和之后都)添加了10個方法,但性能上沒有變化。

26. Methods in derived classes run faster than ones defined in the base class. 派生類中的方法運行起來要快于在基類中定義的同樣的方法。

27. A function call with one parameter and an empty function body takes about the same time as doing 7-8 $localvar++ operations. A similar method call is of course about 15 $localvar++ operations. 調用帶有一個參數的空函數,其花費的時間相當于執行7至8次的局部變量遞增操作。類似的方法調用所花費的時間接近于15次的局部變量遞增操作。

28. Surrounding your string by ‘ instead of " will make things interpret a little faster since php looks for variables inside "…" but not inside ‘…’. Of course you can only do this when you don’t need to have variables in the string. 用單引號代替雙引號來包含字符串,這樣做會更快一些。因為PHP會在雙引號包圍的字符串中搜尋變量,單引號則不會。當然,只有當你不需要在字符串中包含變量時才可以這么做。

29. When echoing strings it’s faster to separate them by comma instead of dot. Note: This only works with echo, which is a function that can take several strings as arguments. 輸出多個字符串時,用逗號代替句點來分隔字符串,速度更快。注意:只有echo能這么做,它是一種可以把多個字符串當作參數的“函數”(譯注:PHP手冊中說echo是語言結構,不是真正的函數,故把函數加上了雙引號)。

30. A PHP script will be served at least 2-10 times slower than a static HTML page by Apache. Try to use more static HTML pages and fewer scripts. Apache解析一個PHP腳本的時間要比解析一個靜態HTML頁面慢2至10倍。盡量多用靜態HTML頁面,少用腳本。

31. Your PHP scripts are recompiled every time unless the scripts are cached. Install a PHP caching product to typically increase performance by 25-100% by removing compile times. 除非腳本可以緩存,否則每次調用時都會重新編譯一次。引入一套PHP緩存機制通常可以提升25%至100%的性能,以免除編譯開銷。

32. Cache as much as possible. Use memcached - memcached is a high-performance memory object caching system intended to speed up dynamic web applications by alleviating database load. OP code caches are useful so that your script does not have to be compiled on every request. 盡量做緩存,可使用memcached。memcached是一款高性能的內存對象緩存系統,可用來加速動態Web應用程序,減輕數據庫負載。對運算碼(OP code)的緩存很有用,使得腳本不必為每個請求做重新編譯。

33. When working with strings and you need to check that the string is either of a certain length you’d understandably would want to use the strlen() function. This function is pretty quick since it’s operation does not perform any calculation but merely return the already known length of a string available in the zval structure (internal C struct used to store variables in PHP). However because strlen() is a function it is still somewhat slow because the function call requires several operations such as lowercase & hashtable lookup followed by the execution of said function. In some instance you can improve the speed of your code by using an isset() trick. 當操作字符串并需要檢驗其長度是否滿足某種要求時,你想當然地會使用strlen()函數。此函數執行起來相當快,因為它不做任何計算,只返回在zval結構(C的內置數據結構,用于存儲PHP變量)中存儲的已知字符串長度。但是,由于strlen()是函數,多多少少會有些慢,因為函數調用會經過諸多步驟,如字母小寫化(譯注:指函數名小寫化,PHP不區分函數名大小寫)、哈希查找,會跟隨被調用的函數一起執行。在某些情況下,你可以使用isset()技巧加速執行你的代碼。

Ex.(舉例如下) if (strlen($foo) < 5) { echo "Foo is too short"; } vs.(與下面的技巧做比較) if (!isset($foo{5})) { echo "Foo is too short"; }

Calling isset() happens to be faster then strlen() because unlike strlen(), isset() is a language construct and not a function meaning that it’s execution does not require function lookups and lowercase. This means you have virtually no overhead on top of the actual code that determines the string’s length. 調用isset()恰巧比strlen()快,因為與后者不同的是,isset()作為一種語言結構,意味著它的執行不需要函數查找和字母小寫化。也就是說,實際上在檢驗字符串長度的頂層代碼中你沒有花太多開銷。

34. When incrementing or decrementing the value of the variable $i++ happens to be a tad slower then ++$i. This is something PHP specific and does not apply to other languages, so don’t go modifying your C or Java code thinking it’ll suddenly become faster, it won’t. ++$i happens to be faster in PHP because instead of 4 opcodes used for $i++ you only need 3. Post incrementation actually causes in the creation of a temporary var that is then incremented. While pre-incrementation increases the original value directly. This is one of the optimization that opcode optimized like Zend’s PHP optimizer. It is still a good idea to keep in mind since not all opcode optimizers perform this optimization and there are plenty of ISPs and servers running without an opcode optimizer. 當執行變量$i的遞增或遞減時,$i++會比++$i慢一些。這種差異是PHP特有的,并不適用于其他語言,所以請不要修改你的C或Java代碼并指望它們能立即變快,沒用的。++$i更快是因為它只需要3條指令(opcodes),$i++則需要4條指令。后置遞增實際上會產生一個臨時變量,這個臨時變量隨后被遞增。而前置遞增直接在原值上遞增。這是最優化處理的一種,正如Zend的PHP優化器所作的那樣。牢記這個優化處理不失為一個好主意,因為并不是所有的指令優化器都會做同樣的優化處理,并且存在大量沒有裝配指令優化器的互聯網服務提供商(ISPs)和服務器。

35. Not everything has to be OOP, often it is too much overhead, each method and object call consumes a lot of memory. 并不是事必面向對象(OOP),面向對象往往開銷很大,每個方法和對象調用都會消耗很多內存。

36. Do not implement every data structure as a class, arrays are useful, too. 并非要用類實現所有的數據結構,數組也很有用。

37. Don’t split methods too much, think, which code you will really re-use. 不要把方法細分得過多,仔細想想你真正打算重用的是哪些代碼?

38. You can always split the code of a method later, when needed. 當你需要時,你總能把代碼分解成方法。

39. Make use of the countless predefined functions. 盡量采用大量的PHP內置函數。

40. If you have very time consuming functions in your code, consider writing them as C extensions. 如果在代碼中存在大量耗時的函數,你可以考慮用C擴展的方式實現它們。

41. Profile your code. A profiler shows you, which parts of your code consumes how many time. The Xdebug debugger already contains a profiler. Profiling shows you the bottlenecks in overview. 評估檢驗(profile)你的代碼。檢驗器會告訴你,代碼的哪些部分消耗了多少時間。Xdebug調試器包含了檢驗程序,評估檢驗總體上可以顯示出代碼的瓶頸。

42. mod_gzip which is available as an Apache module compresses your data on the fly and can reduce the data to transfer up to 80%. mod_zip可作為Apache模塊,用來即時壓縮你的數據,并可讓數據傳輸量降低80%。

43. Excellent Article (http://phplens.com/lens/php-book/optimizing-debugging-php.php)about optimizing php by John Lim 另一篇優化PHP的精彩文章,由John Lim撰寫。

?

轉自:http://www.cnblogs.com/xin478/archive/2008/09/10/1288657.html

轉載于:https://www.cnblogs.com/wenzichiqingwa/archive/2012/12/04/2800769.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/377040.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/377040.shtml
英文地址,請注明出處:http://en.pswp.cn/news/377040.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Iptables入門教程

轉自&#xff1a;http://drops.wooyun.org/tips/1424 linux的包過濾功能&#xff0c;即linux防火墻&#xff0c;它由netfilter 和 iptables 兩個組件組成。 netfilter 組件也稱為內核空間&#xff0c;是內核的一部分&#xff0c;由一些信息包過濾表組成&#xff0c;這些表包含內…

《線程管理:傳遞參數、確定線程數量、線程標識》

參考《c Concurrency In Action 》第二章做的筆記 目錄傳遞參數量產線程線程標識傳遞參數 thread構造函數的附加參數會拷貝至新線程的內存空間中&#xff0c;即使函數中的采納數是引用類型&#xff0c;拷貝操作也會執行。如果我們期待傳入一個引用&#xff0c;必須使用std::re…

手把手玩轉win8開發系列課程(14)

這節的議程就是——添加appbar appbar是出現在哪兒了&#xff0c;出現在屏幕的底部。他能使用戶能用手勢或者使用鼠標操作程序。metro UI 重點是在主要的控件使用許多控件&#xff0c;使其用戶使用win8電腦更加的方便。而appBar使其用戶體驗更好。在這節中&#xff0c;我將告訴…

No identities are available for signing 的解決辦法

今天重新上傳做好的app提交到app store&#xff0c;結果就出現標題上的錯誤。“No identities are available for signing”。 以后碰到這樣的問題按照下面幾個步驟來做&#xff1a; 進入Distribution -----下載發布證書 -----雙擊安裝-----重啟Xcode就能上傳了 其他細節 如果再…

半連接反連接

半連接&反連接 1. 半連接 半連接返回左表中與右表至少匹配一次的數據行&#xff0c;通常體現為 EXISTS 或者 IN 子查詢。左表驅動右表。只返回左表的數據&#xff0c;右表作為篩選條件。 可以用 EXISTS、 IN 或者 ANY 舉例&#xff1a;表t1和表t2做半連接&#xff0c;t…

匿名方法和Lambda表達式

出于MVVM學習的需要&#xff0c;復習下匿名方法和Lambda表達式&#xff0c;因為之前用的也比較少&#xff0c;所以用的也不是很熟練&#xff0c;Baidu下相關的知識&#xff0c;寫了這個Demo&#xff0c;目標是用簡單的方法展示這個怎么用。 這里偏重的和LINQ中的Lambda表達式 …

爛橘子

Problem Statement: 問題陳述&#xff1a; Given a matrix of dimension r*c where each cell in the matrix can have values 0, 1 or 2 which has the following meaning: 給定尺寸r * C的矩陣&#xff0c;其中矩陣中的每個單元可以具有其具有以下含義的值0&#xff0c;1或2…

android junit 測試程序

http://blog.csdn.net/to_cm/article/details/5704783 Assert.assertEquals(2, t); 斷言轉載于:https://www.cnblogs.com/wjw334/p/3714120.html

MySQL 8.0.22執行器源碼分析HashJoin —— BuildHashTable函數細節步驟

BuildHashTable函數細節步驟 該函數位置處于hash_join_iterator.cc 403 ~ 560行 step1&#xff1a;如果被驅動表迭代器沒有更多的行數&#xff0c;更新m_state為EOR&#xff0c;然后返回false&#xff0c;表明創建hash表失敗 if (!m_build_iterator_has_more_rows) {m_state…

《那些年啊,那些事——一個程序員的奮斗史》——125

距離離職交接的一個月時間還剩幾天&#xff0c;本來應該是平淡無事的&#xff0c;卻沒想到最后還是波瀾四起。昨天下班前&#xff0c;公司突然停了電。這本是件普通得不能再普通的事情&#xff0c;可沒想到過了一會來電了&#xff0c;或許是波峰電壓太大&#xff0c;或許是穩壓…

python中的元類_Python中的元類

python中的元類Python元類 (Python metaclass) A metaclass is the class of a class. A class defines how an instance of a class i.e.; an object behaves whilst a metaclass defines how a class behaves. A class is an instance of a metaclass. 元類是類的類。 一個類…

MySQL 8.0.22執行器源碼分析HashJoin —— 一些初始化函數的細節步驟

目錄InitRowBuffer&#xff08;101行~126行&#xff09;InitProbeIterator&#xff08;142行~153行&#xff09;*HashJoinIterator* 的Init&#xff08;155行~240行&#xff09;InitializeChunkFiles&#xff08;364行~401行&#xff09;InitWritingToProbeRowSavingFile&#…

c語言的宏定義學習筆記

宏定義 在預處理之前&#xff0c;c預處理器會對代碼進行翻譯&#xff0c;譬如用blank替換注釋&#xff0c;去掉多余的空格&#xff0c;刪除末尾的\來拼接行等。 例如&#xff1a; int /*注釋*/ x; 會被翻譯成 int x; printf("this is a s\ entence."); 會被翻譯成 pr…

攝氏溫度轉換華氏溫度_什么是攝氏溫度?

攝氏溫度轉換華氏溫度攝氏溫度 (Celsius) Celsius is a temperature measuring scale which as a SI unit derived from the seven base units stated and described by the International System of Units (SI). 攝氏溫度是一種溫度測量刻度&#xff0c;它是由國際單位制(SI)所…

別人的算法學習之路

http://www.cnblogs.com/figure9/p/3708351.html 我的算法學習之路 關于 嚴格來說&#xff0c;本文題目應該是我的數據結構和算法學習之路&#xff0c;但這個寫法實在太繞口——況且CS中的算法往往暗指數據結構和算法&#xff08;例如算法導論指的實際上是數據結構和算法導論&a…

git config命令使用第二篇——section操作,多個key值操作,使用正則

接上一篇&#xff0c;git config命令使用第一篇——介紹&#xff0c;基本操作&#xff0c;增刪改查:http://blog.csdn.net/hutaoer06051/article/details/8275069 1. 刪除一個section 命令參數 --remove-section 格式&#xff1a;git config [--local|--global|--system] --rem…

MySQL面試準備——64頁pdf

本筆記為以前整理的零碎的關于Mysql的知識點&#xff0c;有深入源碼的也有淺層的八股。已經被我整理成了一個pdf。 實習崗位正好也是和數據庫內核有關的&#xff0c;之后應該還會更新。做個整理&#xff0c;方便秋招的時候快速回顧吧。 鏈接&#xff1a;鏈接 提取碼&#xff1a…

python點圖_Python | 點圖

python點圖The dot plot is a type of data representation in which each data-point in the figure is represented as a dot. Dot plot underlies discrete functions unlike a continuous function in a line plot. Each value could be correlated but cannot be connecte…

SAP-MM:發票、貸方憑證、事后借記、后續貸記

發票和事后借記 相同點&#xff1a;增加對供應商的應付款 不同點&#xff1a;針對同一訂單收貨&#xff0c;發票要先于事后借記&#xff08;事后借記是對供應商后期發票金額的補充&#xff09;&#xff1b;發票和金額、訂單數量有關系&#xff0c;而事后借記只是訂單金額調整的…

Dijkstra for MapReduce (1)

<math xmlns"http://www.w3.org/1998/Math/MathML"><mi>x</mi><mo>,</mo><mi>y</mi><mo>&#x2208;<!-- ∈ --></mo><mi>X</mi> </math> 準備研究一下Dijkstra最短路徑算法Hadoop上…