search
HomeBackend DevelopmentPHP TutorialPHP网站开发使用技巧小结!

静态调用的成员一定要定义成 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();
?>



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

[size=+2]使用类常量 (PHP5 ONLY)

贴士:PHP 5 新功能,类似于 C++ 的 const。

使用类常量的好处是:

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

[size=+2](暂时)不要使用 require/include_once

require/include_once 每次被调用的时候都会打开目标文件!

- 如果用绝对路径的话,PHP 5.2/6.0 不存在这个问题
- 新版的 APC 缓存系统已经解决这个问题

文件 I/O 增加 => 效率降低

如果需要,可以自行检查文件是否已被 require/include。

[size=+2]不要调用毫无意义的函数

有对应的常量的时候,不要使用函数。

QUOTE:

// PHP CODE Highliting for CU by dZ902

<?php
php_uname('s') == PHP_OS;
php_version() == PHP_VERSION;
php_sapi_name() == PHP_SAPI;
?>


虽然使用不多,但是效率提升大概在 3500% 左右。

[size=+2]最快的 Win32 检查

QUOTE:

// PHP CODE Highliting for CU by dZ902

<?php
$is_win = DIRECTORY_SEPARATOR == '//';
?>



- 不用函数
- Win98/NT/2000/XP/Vista/Longhorn/Shorthorn/Whistler...通用
- 一直可用

[size=+2]时间问题 (PHP>5.1.0 ONLY)

你如何在你的软件中得知现在的时间?简单,「time() time() again, you ask me...」。

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

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

[size=+2]加速 PCRE

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

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

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

例如:
 

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



[size=+2]加速 strtr

如果需要转换的全是单个字符的时候,用字符串而不是数组来做 strtr:

QUOTE:

// PHP CODE Highliting for CU by dZ902

<?php
$addr = strtr($addr, "abcd", "efgh"); // good
$addr = strtr($addr, array('a' => 'e',
                           // ...
                           )); // bad
?>



效率提升:10 倍。

[size=+2]不要做无谓的替换

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

- 用 strpos 先查找(非常快),看是否需要替换,如果需要,再替换

效率:

- 如果需要替换:效率几乎相等,差别在 0.1% 左右。
- 如果不需要替换:用 strpos 快 200%。

[size=+2]邪恶的 @ 操作符

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

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

[size=+2]善用 strncmp

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

[size=+2]慎用 substr_compare (PHP5 ONLY)

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

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

[size=+2]不要用常量代替字符串

为什么:

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

效率差别:700%。

[size=+2]不要把 count/strlen/sizeof 放到 for 循环的条件语句中

贴士:我的个人做法

QUOTE:

// PHP CODE Highliting for CU by dZ902

<?php
for ($i = 0, $max = count($array);$i < $max; ++$i);
?>



效率提升相对于:

- count 50%
- strlen 75%

[size=+2]短的代码不一定快

QUOTE:

// PHP CODE Highliting for CU by dZ902

<?php
// longest
if ($a == $b) {
    $str .= $a;
} else {
    $str .= $b;
}

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

// short
$str .= ($a == $b ? $a : $b);
?>



你觉得哪个快?

效率比较:

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

不可思议?再来一个:

QUOTE:

// PHP CODE Highliting for CU by dZ902

<?php
// original
$d = dir('.');
while (($entry = $d->read()) !== false) {
    if ($entry == '.' || $entry == '..') {
        continue;
    }
}

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

// versus (include . and ..)
scandir('.');
?>



哪个快?

效率比较:

- original: 3.37
- glob: 6.28
- scandir: 3.42
- original without OO: 3.14
- SPL (PHP5): 3.95

画外音:从此也可以看出来 PHP5 的面向对象效率提高了很多,效率已经和纯函数差得不太多了。

[size=+2]提高 PHP 文件访问效率

需要包含其他 PHP 文件的时候,使用完整路径,或者容易转换的相对路径。

QUOTE:

// PHP CODE Highliting for CU by dZ902

<?php

include 'file.php'; // bad approach

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

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

?>



[size=+2]物尽其用

PHP 有很多扩展和函数可用,在实现一个功能的之前,应该看看 PHP 是否有了这个功能?是否有更简单的实现?

QUOTE:

// PHP CODE Highliting for CU by dZ902

<?php
$filename = "./somepic.gif";
$handle = fopen($filename, "rb");
$contents = fread($handle, filesize($filename));
fclose($handle);

// vs. much simpler

file_get_contents('./somepic.gif');
?>



[size=+2]关于PHP引用的技巧

引用可以:

- 简化对复杂结构数据的访问
- 优化内存使用

QUOTE:

// PHP CODE Highliting for CU by dZ902

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



QUOTE:

// PHP CODE Highliting for CU by dZ902

<?php
$a = 'large string';

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

// more efficient solution
function a(&$str)
{
    $str .= 'something';
}
?>


Statement
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
Working with Flash Session Data in LaravelWorking with Flash Session Data in LaravelMar 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 APIscURL in PHP: How to Use the PHP cURL Extension in REST APIsMar 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.

PHP Logging: Best Practices for PHP Log AnalysisPHP Logging: Best Practices for PHP Log AnalysisMar 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

Simplified HTTP Response Mocking in Laravel TestsSimplified HTTP Response Mocking in Laravel TestsMar 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 CodeCanyon12 Best PHP Chat Scripts on CodeCanyonMar 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

Customizing/Extending Frameworks: How to add custom functionality.Customizing/Extending Frameworks: How to add custom functionality.Mar 28, 2025 pm 05:12 PM

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

See all articles

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)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),