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.他会告诉你脚本运行的耗时分析和哪个部分用了最多的时间。这让你很简单就能找到你代码中的瓶颈。

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-

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.

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' =>

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

Laravel's service container and service providers are fundamental to its architecture. This article explores service containers, details service provider creation, registration, and demonstrates practical usage with examples. We'll begin with an ove

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 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

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Chinese version
Chinese version, very easy to use

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Linux new version
SublimeText3 Linux latest version