您的位置 首页 php

PHP代码中常用的优化策略

1、如果能将类的方法定义成 static ,就尽量定义成static,它的速度会提升将近4倍。

2、$row[‘id’] 的速度是$row[id]的7倍。

3、echo 比 print 快,并且使用echo的多重参数(译注:指用逗号而不是句点)代替字符串连接,比如echo $str1,$str2。

4、在执行for循环之前确定最大循环数,不要每循环一次都计算最大值,最好运用foreach代替。

5、注销那些不用的变量尤其是大数组,以便释放内存。

6、尽量避免使用__get,__set,__autoload。

7、require_once()代价昂贵。

8、include文件时尽量使用绝对路径,因为它避免了PHP去include_path里查找文件的速度,解析操作系统路径所需的时间会更少。

9、如果你想知道脚本开始执行(译注:即服务器端收到客户端请求)的时刻,使用$_SERVER[‘REQUEST_TIME’]要好于time()。

10、函数代替正则表达式完成相同功能。

11、str_replace函数比preg_replace函数快,但strtr函数的效率是str_replace函数的四倍。

12、如果一个字符串替换函数,可接受数组或字符作为参数,并且参数长度不太长,那么可以考虑额外写一段替换代码,使得每次传递参数是一个字符,而不是只写一行代码接受数组作为查询和替换的参数。

13、使用选择分支语句(译注:即switch case)好于使用多个if,else if语句。

14、用@屏蔽错误消息的做法非常低效,极其低效。

15、打开apache的mod_deflate模块,可以提高网页的浏览速度。

16、数据库连接当使用完毕时应关掉,不要用长连接。

17、错误消息代价昂贵。

18、在方法中递增 局部变量 ,速度是最快的。几乎与在函数中调用局部变量的速度相当。

19、递增一个 全局变量 要比递增一个局部变量慢2倍。

20、递增一个对象属性(如:$this->prop++)要比递增一个局部变量慢3倍。

21、递增一个未预定义的局部变量要比递增一个预定义的局部变量慢9至10倍。

22、仅定义一个局部变量而没在函数中调用它,同样会减慢速度(其程度相当于递增一个局部变量)。PHP大概会检查看是否存在全局变量。

23、方法调用看来与类中定义的方法的数量无关,因为我(在测试方法之前和之后都)添加了10个方法,但性能上没有变化。

24、派生类中的方法运行起来要快于在基类中定义的同样的方法。

25、调用带有一个参数的空函数,其花费的时间相当于执行7至8次的局部变量递增操作。类似的方法调用所花费的时间接近于15次的局部变量递增操作。

26、Apache解析一个PHP脚本的时间要比解析一个静态HTML页面慢2至10倍。尽量多用静态HTML页面,少用脚本。

27、除非脚本可以缓存,否则每次调用时都会重新编译一次。引入一套PHP缓存机制通常可以提升25%至100%的性能,以免除编译开销。

28、尽量做缓存,可使用memcached。memcached是一款高性能的内存对象缓存系统,可用来加速动态Web应用程序,减轻数据库负载。对运算码 (OP code)的缓存很有用,使得脚本不必为每个请求做重新编译。

29、当操作字符串并需要检验其长度是否满足某种要求时,你想当然地会使用strlen()函数。此函数执行起来相当快,因为它不做任何计算,只返回在zval 结构(C的内置数据结构,用于存储PHP变量)中存储的已知字符串长度。但是,由于strlen()是函数,多多少少会有些慢,因为函数调用会经过诸多步骤,如字母小写化(译注:指函数名小写化,PHP不区分函数名大小写)、哈希查找,会跟随被调用的函数一起执行。在某些情况下,你可以使用isset() 技巧加速执行你的代码。

(举例如下)

1

if (strlen($foo) < 5) { echo “Foo is too short”$$ }

(与下面的技巧做比较)

1

if (!isset($foo{5})) { echo “Foo is too short”$$ }

调用isset()恰巧比strlen()快,因为与后者不同的是,isset()作为一种语言结构,意味着它的执行不需要函数查找和字母小写化。也就是说,实际上在检验字符串长度的顶层代码中你没有花太多开销。

34、当执行变量$i的递增或递减时,$i++会比++$i慢一些。这种差异是PHP特有的,并不适用于其他语言,所以请不要修改你的C或Java 代码并指望它们能立即变快,没用的。++$i更快是因为它只需要3条指令(opcodes),$i++则需要4条指令。后置递增实际上会产生一个临时变量,这个临时变量随后被递增。而前置递增直接在原值上递增。这是最优化处理的一种,正如Zend的PHP优化器所作的那样。牢记这个优化处理不失为一个好主意,因为并不是所有的指令优化器都会做同样的优化处理,并且存在大量没有装配指令优化器的互联网服务提供商(ISPs)和服务器。

35、并不是事必面向对象(OOP),面向对象往往开销很大,每个方法和对象调用都会消耗很多内存。

36、并非要用类实现所有的数据结构,数组也很有用。

37、不要把方法细分得过多,仔细想想你真正打算重用的是哪些代码?

38、当你需要时,你总能把代码分解成方法。

39、尽量采用大量的PHP内置函数。

40、如果在代码中存在大量耗时的函数,你可以考虑用C扩展的方式实现它们。

41、评估检验(profile)你的代码。检验器会告诉你,代码的哪些部分消耗了多少时间。Xdebug调试器包含了检验程序,评估检验总体上可以显示出代码的瓶颈。

42、mod_zip可作为Apache模块,用来即时压缩你的数据,并可让数据传输量降低80%。

43、在可以用file_get_contents替代file、fopen、feof、fgets等系列方法的情况下,尽量用 file_get_contents,因为他的效率高得多!但是要注意file_get_contents在打开一个URL文件时候的PHP版本问题;

44、尽量的少进行文件操作,虽然PHP的文件操作效率也不低的;

45、优化Select SQL语句,在可能的情况下尽量少的进行Insert、Update操作(在update上,我被恶批过);

46、尽可能的使用PHP内部函数(但是我却为了找个PHP里面不存在的函数,浪费了本可以写出一个自定义函数的时间,经验问题啊!);

47、循环内部不要声明变量,尤其是大变量:对象(这好像不只是PHP里面要注意的问题吧?);

48、多维数组尽量不要循环嵌套赋值;

49、在可以用PHP内部字符串操作函数的情况下,不要用正则表达式;

50、foreach效率更高,尽量用foreach代替while和for循环;

文章来源:智云一二三科技

文章标题:PHP代码中常用的优化策略

文章地址:https://www.zhihuclub.com/78087.shtml

关于作者: 智云科技

热门文章

评论已关闭

35条评论

  1. Still, if you use ED pills frequently, the low price per dose is worth these additional charges

  2. However, I consider it possible that some people of Globocnik s staff in Lublin had gone to Warsaw with the order to supervise the transport of able Jews and to process it In the station was a train full of Jews, some dead, some still alive that too looked as if it had been there for days

  3. Kurian Mathew Tharakan is the founder of sales and marketing strategy firm StrategyPeak Sales Marketing Advisors, a 27 year veteran of the sales and marketing industry, and the author of the Amazon bestseller, The Seven Essential Stories Charismatic Leaders Tell

  4. Best for Newbies RexMD Most of the best Cialis sellers on the internet are located in China

  5. Traditional Persian medicine is one of the most well-known categories of traditional medicine using herbal medicine as one of the main therapeutic modalities 71. My current RE says that femara injectables is not near as effective as a full blown injectable cycle since with the former, injectables are administered later in the cycle after femara than with the latter ie.

  6. Expert Rev Anticancer Ther 2010; 10 895 901 p21 blocks progression of the cell cycle at G1 S and is involved in G2 M phase arrest Dulic et al, 1998

  7. select patients with prior cancer for a biologic treatment, as it does not increase the rate of incident malignancies Nolvadex for sale is available in the form of coated tablets

  8. Monitor Closely 1 chloramphenicol increases levels of estrogens esterified by affecting hepatic intestinal enzyme CYP3A4 metabolism

  9. 0065 A patient is treated according to the invention if one or preferably more symptoms of cancer as described herein are eliminated or reduced in severity, or prevented from progressing or developing further Participants were assigned to receive one of the following aromatase inhibitors AIs, either anastrozole, exemestane, or letrozole, tamoxifen, fulvestrant 500 mg, or fulvestrant 250 mg

  10. Anabolic effect of genistein on bone metabolism in the femoral metaphyseal tissues of elderly rats is inhibited by the anti estrogen tamoxifen

  11. In this section we include studies of procedures to treat uterine fibroids including uterine artery embolization UAE and occlusion, high intensity focused ultrasound HIFU for fibroid ablation, and radiofrequency fibroid ablation

  12. Patients at risk for hepatitis B or histoplasmosis infections will also be tested before receiving Humira Thus, constitutive promoters such as those from the X linked phosphoglycerate kinase 1 locus PGK, or the human cytomegalovirus CMV immediate early promoter enhancers fused to a minimal chicken beta actin gene promoter CAG are often used to drive expression in all tissues

  13. The NYCRIS cancer register identified a further nine endometrial cancers, within a year of the initial appointment in RAC, which were not captured by initial investigations

  14. Les Е“ufs ont Г©tГ© prГ©levГ©s tous les jours jusqu Г  ont Г©tГ© dГ©posГ©s

  15. Researcher Aysegul Yildiz, MD, and colleagues of Turkey s Dokuz Eylul University Medical School treated 50 manic bipolar patients with either tamoxifen or placebo for three weeks

  16. It seems likely that several different mechanisms may be operative in various subsets of individuals

  17. 10 Phenylephrine can be administered as a continuous infusion but is more often used for intermittent IV bolus dosing in distributive shock

  18. 128 130 Another intriguing way to investigate the HER2 status is the recently released HERmark Monogram Biosciences, San Francisco, CA, USA breast cancer assay

  19. It is important to note that with the emergence of significantly improved treatments, the issue of crossover is being addressed in many trials and is not unique to this trial

  20. This will also help you keep your blood sugar levels balanced which is essential for optimum health and functionality, pregnant or not

  21. The important message for women is that it may never be too late for many breast cancer survivors to do more to protect themselves against the ongoing risk of disease recurrence, said Paul Goss, M Portal Hypertension and Related Complications Diagnosis and Management

  22. When a worsening heart failure event is defined as death, hospitalization for heart failure, an emergent or urgent heart failure visit requiring intravenous treatment, diuretic intensification or deterioration in NYHA functional class, a worsening heart failure event occurred in 802 patients in the placebo group, but in only 609 patients in the empagliflozin group, corresponding to annualized rates of 48

网站地图