Home php教程 php手册 PHP 的一些高效技巧

PHP 的一些高效技巧

Jun 13, 2016 am 10:19 AM
php of

静态调用的成员一定要定义成 static (PHP5 ONLY)
贴士:PHP 5 引入了静态成员的概念,作用和 PHP 4 的函数内部静态变量一致,但前者是作为类的成员来使用。静态变量和 Ruby 的类变量(class variable)差不多,所有类的实例共享同一个静态变量。

QUOTE:

// PHP CODE Highliting for CU by dZ902

<?php
class foo {
     function bar() {
         echo 'foobar';
     }
}

$foo = new foo;

// instance way

$foo->bar();

// static way

foo::bar();
?>
Copy after login

静态地调用非 static 成员,效率会比静态地调用 static 成员慢 50-60%。主要是因为前者会产生 E_STRICT 警告,内部也需要做转换。


使用类常量 (PHP5 ONLY) 贴士:PHP 5 新功能,类似于 C++ 的 const。


使用类常量的好处是:


- 编译时解析,没有额外开销
- 杂凑表更小,所以内部查找更快
- 类常量仅存在于特定「命名空间」,所以杂凑名更短
- 代码更干净,使除错更方便


(暂时)不要使用 require/include_once


require/include_once 每次被调用的时候都会打开目标文件!
- 如果用绝对路径的话,PHP 5.2/6.0 不存在这个问题
- 新版的 APC 缓存系统已经解决这个问题
文件 I/O 增加 => 效率降低
如果需要,可以自行检查文件是否已被 require/include。
不要调用毫无意义的函数 有对应的常量的时候,不要使用函数。
<?php
php_uname('s') == PHP_OS;
php_version() == PHP_VERSION;
php_sapi_name() == PHP_SAPI;
?>
Copy after login
虽然使用不多,但是效率提升大概在 3500% 左右。 最快的 Win32 检查:
<?php
$is_win = DIRECTORY_SEPARATOR == '\\';
?>
Copy after login
- 不用函数
- Win98/NT/2000/XP/Vista/Longhorn/Shorthorn/Whistler...通用
- 一直可用
时间问题 (PHP>5.1.0 ONLY) 你如何在你的软件中得知现在的时间?简单,「time() time() again, you ask me...」。

不过总归会调用函数,慢。

现在好了,用 $_SERVER['REQUEST_TIME'],不用调用函数,又省了。

加速 PCRE - 对于不用保存的结果,不用 (),一律用 (?


这样 PHP 不用为符合的内容分配内存,省。效率提升 15% 左右。


- 能不用正则,就不用正则,在分析的时候仔细阅读手册「字符串函数」部分。有没有你漏掉的好用的函数?


例如:


strpbrk()
strncasecmp()
strpos()/strrpos()/stripos()/strripos()

加速 strtr

如果需要转换的全是单个字符的时候,用字符串而不是数组来做 strtr:
<?php
$addr = strtr($addr, "abcd", "efgh"); // good
$addr = strtr($addr, array('a' => 'e',
                            // ...
                            )); // bad
?>
Copy after login
效率提升:10 倍。

不要做无谓的替换 即使没有替换,str_replace 也会为其参数分配内存。很慢!解决办法:

- 用 strpos 先查找(非常快),看是否需要替换,如果需要,再替换
效率:
- 如果需要替换:效率几乎相等,差别在 0.1% 左右。
- 如果不需要替换:用 strpos 快 200%。
邪恶的 @ 操作符

不要滥用 @ 操作符。虽然 @ 看上去很简单,但是实际上后台有很多操作。用 @ 比起不用 @,效率差距:3 倍。


特别不要在循环中使用 @,在 5 次循环的测试中,即使是先用 error_reporting(0) 关掉错误,在循环完成后再打开,都比用 @ 快。


善用 strncmp

当需要对比「前 n 个字符」是否一样的时候,用 strncmp/strncasecmp,而不是 substr/strtolower,更不是 PCRE,更千万别提 ereg。strncmp/strncasecmp 效率最高(虽然高得不多)。


慎用 substr_compare (PHP5 ONLY)

按照上面的道理,substr_compare 应该比先 substr 再比较快咯。答案是否定的,除非:


- 无视大小写的比较
- 比较较大的字符串


不要用常量代替字符串
为什么:


- 需要查询杂凑表两次
- 需要把常量名转换为小写(进行第二次查询的时候)
- 生成 E_NOTICE 警告
- 会建立临时字符串

效率差别:700%。

不要把 count/strlen/sizeof 放到 for 循环的条件语句中 贴士:我的个人做法
<?php
for ($i = 0, $max = count($array);$i < $max; ++$i);
?>
Copy after login

效率提升相对于:
- count 50%
- strlen 75%
短的代码不一定快
<?php
// longest
if ($a == $b) {
     $str .= $a;
} else {
     $str .= $b;
}

// longer
if ($a == $b) {
     $str .= $a;
}
$str .= $b;

// short
$str .= ($a == $b ? $a : $b);
?>
Copy after login
你觉得哪个快?

效率比较:

- longest: 4.27
- longer: 4.43
- short: 4.76

不可思议?再来一个:
<?php
// original
$d = dir('.');
while (($entry = $d->read()) !== false) {
     if ($entry == '.' || $entry == '..') {
         continue;
     }
}

// versus
glob('./*');

// versus (include . and ..)
scandir('.');
?>
Copy after login
哪个快?


效率比较:
- original: 3.37
- glob: 6.28
- scandir: 3.42
- original without OO: 3.14
- SPL (PHP5): 3.95
画外音:从此也可以看出来 PHP5 的面向对象效率提高了很多,效率已经和纯函数差得不太多了。
提高 PHP 文件访问效率
需要包含其他 PHP 文件的时候,使用完整路径,或者容易转换的相对路径。

<?php

include 'file.php'; // bad approach

incldue './file.php'; // good

include '/path/to/file.php'; // ideal

?>
Copy after login
物尽其用
PHP 有很多扩展和函数可用,在实现一个功能的之前,应该看看 PHP 是否有了这个功能?是否有更简单的实现?
<?php
$filename = "./somepic.gif";
$handle = fopen($filename, "rb");
$contents = fread($handle, filesize($filename));
fclose($handle);

// vs. much simpler

file_get_contents('./somepic.gif');
?>
Copy after login
关于引用的技巧 引用可以:
- 简化对复杂结构数据的访问
- 优化内存使用
<?php
$a['b']['c'] = array();

// slow 2 extra hash lookups per access
for ($i = 0; $i < 5; ++$i)
     $a['b']['c'][$i] = $i;

// much faster reference based approach
$ref =& $a['b']['c'];
for ($i = 0; $i < 5; ++$i)
     $ref[$i] = $i;
?>
Copy after login
<?php
$a = 'large string';

// memory intensive approach
function a($str)
{
     return $str.'something';
}

// more efficient solution
function a(&$str)
{
     $str .= 'something';
}
?>
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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles