Home Backend Development PHP Tutorial [译]Speeding up your PHP scripts

[译]Speeding up your PHP scripts

Jun 23, 2016 pm 02:32 PM

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 < count($array); $i++)for($i=0; $i < $count; $i++){echo array[$i];}Simple conditionals简单条件判断It's better to use a switch statement instead of if/else if/else when you're using simple conditionals.如果你的条件比较简单,使用 switch 比用  if/else if/else 好多了。Includes & requiresIncludes 和 requiresThere are several ways to gain some speed in this are; first of all drop the use of require_once it's much slower than include_once. Try to use full paths in your includes and requires, it'll spare the server some time on resolving the paths.这儿有几种方法可以加速: 首先,用require_once比include_once慢多了。尽量在你的包含和引用中用全路径,这样可以省掉解析路径的开销。There are 3 ways of doing this; You could just simply set the include path.有三种方式可以用;你只要简单的设置一下include的路径。 // Works as of PHP 4.3.0set_include_path('/inc'); // Works in all PHP versionsini_set('include_path', '/inc'); Or you could create a variable with the include path and concatenate it at the start of an include.或者新建个用于包含的路径变量,并把它放到include连接起来。$include = '/home/user/www';include ($include . '/library/loader.php'); As a third example; you could also just get the directory path from the current file.第三个例子:你也可以只获取当前文件的路径。$dir = dirname(__FILE__);include ($dir . '/library/loader.php'); Handling strings处理字符串Try to make use of as much str_ functions as possible instead of turning to preg_ functions.尽量使用 str_ 函数代替 preg_ 函数。Str_replace is much faster than preg_replace if you're not making use of regex patterns. In turn strstr is faster than using str_replace.要是你不用正则表达式,str_replace比preg_replace快多了。 但是strstr 比 str_replace快。Try to make use of these functions instead of preg_ functions: strpos, strpbrk, strncasecmp.尽量用这些函数来代替preg_函数: strpos, strpbrk, strncasecmp。If you need to check  if a string has a certain length it's better to use the isset trick than using strlen.如果你需要检查一个字符串的长度,巧妙的使用isset比strlen好多了。$str = 'have a nice day';//check if the string has more than 6 characters//slow, checks if the string has less than 7 characters.if(strlen($str) < 7)//fast, if there is no seventh character setif(!isset($str{6}))This is because isset is a language construct, whereas strlen is a function that is looked up.这是因为,isset是一种语言结构,而strlen是一个函数。Ofcourse there are several tools than can help you; use a code profiler.当然有一些工具可以帮忙:用 a code profiler。They will tell you which how much time is spent parsing your script and which part requires the most time.  This makes it easy to find bottlenecks in your code.他会告诉你脚本运行的耗时分析和哪个部分用了最多的时间。这让你很简单就能找到你代码中的瓶颈。
Copy after login
Statement of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Two Point Museum: All Exhibits And Where To Find Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Working with Flash Session Data in Laravel Working with Flash Session Data in Laravel Mar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Simplified HTTP Response Mocking in Laravel Tests Simplified HTTP Response Mocking in Laravel Tests Mar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

12 Best PHP Chat Scripts on CodeCanyon 12 Best PHP Chat Scripts on CodeCanyon Mar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

PHP Logging: Best Practices for PHP Log Analysis PHP Logging: Best Practices for PHP Log Analysis Mar 10, 2025 pm 02:32 PM

PHP logging is essential for monitoring and debugging web applications, as well as capturing critical events, errors, and runtime behavior. It provides valuable insights into system performance, helps identify issues, and supports faster troubleshoot

HTTP Method Verification in Laravel HTTP Method Verification in Laravel Mar 05, 2025 pm 04:14 PM

Laravel simplifies HTTP verb handling in incoming requests, streamlining diverse operation management within your applications. The method() and isMethod() methods efficiently identify and validate request types. This feature is crucial for building

Discover File Downloads in Laravel with Storage::download Discover File Downloads in Laravel with Storage::download Mar 06, 2025 am 02:22 AM

The Storage::download method of the Laravel framework provides a concise API for safely handling file downloads while managing abstractions of file storage. Here is an example of using Storage::download() in the example controller:

See all articles