欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

[译]Speeding up your PHP scripts

程序员文章站 2022-05-16 13:26:50
...
I've been coding in PHP ever since I was 13, over the years I have seen many different coding styles and standards being used. However most of them weren't optimised.

我从13岁就开始编写PHP代码,这些年里我见过很多不同风格不同标准的代码。然而大多时候他们还没有进行过优化。

This time I'd like to talk about different ways on how you can speed up your scripts by optimizing your code to reduce your server load.
这次我想聊聊如何让你的代码更优化,以降低服务器的负载。

Coding tips

编码要点


Quotes

引号

Try using single quotes as much as possible, it's faster than double quotes because PHP searches for variables in text surrounded in double quotes.

尽可能的使用单引号,它比双引号快,因为PHP会在双引号包围的字符串中搜索变量。

Using single quotes in arrays is also recommended since it's faster than calling it with double or no quotes.

在数组中也推荐使用单引号,因为它要比双引号和不加引号快。

Echo VS. print

Echo 与 print

Echo is faster than print, if you're using concatenation in your echo command then you could optimise it further by using multiple parameters instead of concatenation.

Echo 比 print 快,尽可能的使用单引号,如果你在echo 命令中要用到连接,那就把它优化成多个参数相连。

The print function can't handle multiple parameters so don't even try.

print函数不能处理多个参数,所以,请别尝试。

$name = 'zenk0';echo 'the user ', $name, ' has been selected for a special event.';//slower and more widely usedecho 'The user ' . $name . ' has been selected for a special event.';For loops循环Define your count variable before you start looping instead of in your loop. If you don't do this then your count function will be repeated everytime a loop happens.不要在循环体内,而是在循环体外定义 count 变量。如果不这样,你的计数函数每次循环都会调用。$array = array('one', 'two', 'three');$count = count($array);//slow : for($i=0; $i