


1. When file_get_contents can be used instead of file, fopen, feof, fgets and other series of methods, try to use file_get_contents because it is much more efficient! But please pay attention to the PHP version problem of file_get_contents when opening a URL file;
2. Try to perform as few file operations as possible, although PHP's file operation efficiency is not low;
3. Optimization SELECT SQL statements, perform as few INSERT and UPDATE operations as possible (I was criticized on UPDATE);
4. Use PHP internal functions as much as possible (but I just want to find A function that does not exist in PHP is a waste of time that could be used to write a custom function. It’s a matter of experience! );
5. Don’t declare variables inside the loop, especially large variables: objects (this seems like Isn’t it just a problem that needs to be paid attention to in PHP? );
6. Try not to nest nested assignments in multi-dimensional arrays;
7. You can use PHP In the case of internal string manipulation functions, do not use regular expressions;
8. foreach is more efficient, try to use foreach instead of while and for loops;
9. Use single quotes instead of double quotes to quote strings;
10. Use i+=1 instead of i=i+1. It conforms to the habits of c/c++ and is highly efficient;
11. Global variables should be unset()ed after use;
are called statically Members must be defined as static (PHP5 ONLY)
Tips: PHP5 introduces the concept of static members, which has the same function as the static variables inside the function of PHP4, but the former is used as a member of the class. Static variables are similar to Ruby's class variables. All instances of a class share the same static variable. The efficiency of statically calling non-static members will be 50-60% slower than statically calling static members. Mainly because the former will generate an E_STRICT warning and needs to be converted internally.
class foo {
function bar() {
echo 'foobar';
}
}
$foo = new foo;
// instance way
$foo->bar();
// static way
foo::bar();
?>
Use class constants (PHP5 ONLY)
Tips: PHP5 new function, similar to C++ const.
The benefits of using class constants are:
- Compile-time analysis, no additional overhead
- The hash table is smaller, so internal lookups are faster
- Class constants only exist in a specific "namespace", so the hash name is shorter
- The code is cleaner, making debugging easier
(temporarily) Do not use it require/include_once
require/include_once will open the target file every time it is called!
- If you use absolute paths, PHP 5.2/6.0 does not have this problem
- The new version of the APC cache system has solved this problem
File I/O increased => ; Reduced efficiency
If necessary, you can check whether the file has been require/included.
Don’t call meaningless functions
Don’t use functions when there are corresponding constants.
php_uname('s') == PHP_OS;
php_version() == PHP_VERSION;
php_sapi_name() == PHP_SAPI;
?>
Although it is not used much, the efficiency improvement is about 3500%.
The fastest Win32 check
$is_win = DIRECTORY_SEPARATOR == '\';
?>
- No need for functions
- Win98/NT/2000/XP/Vista/Longhorn/Shorthorn/Whistler... Universal
- always available
time Question (PHP>5.1.0 ONLY)
How do you know the current time in your software? Simple, "time() time() again, you ask me...".
But it will always call the function, which is slow.
Now it’s better, use $_SERVER['REQUEST_TIME'], no need to call the function, save again.
Accelerate PCRE
- For results that do not need to be saved, do not use (), always use (?:)
In this way, PHP does not need to match the content Allocate memory, save. The efficiency is improved by about 15%.
- If you can use regular expressions, do not use regular expressions. Please read the "String Functions" section of the manual carefully when analyzing.Are there any useful functions that you missed?
For example:
strpbrk()
strncasecmp()
strpos()/strrpos()/stripos()/strripos()
Speed up strtr
If all you need to convert is a single character, use a string instead of an array to do strtr:
$addr = strtr($addr, "abcd", "efgh"); // good
$addr = strtr($addr, array('a' => 'e',
// . ..
)); // bad
?>
Efficiency improvement: 10 times.
Don’t do unnecessary substitutions
Even without substitution, str_replace will allocate memory for its parameters. Very slow! Solution:
- Use strpos to search first (very fast) to see if it needs to be replaced. If necessary, replace
Efficiency:
- If it needs to be replaced: the efficiency is almost Equal, the difference is about 0.1%.
- If no replacement is needed: use strpos 200% faster.
The evil @ operator
Don’t abuse the @ operator. Although @ looks simple, there are actually many operations behind the scenes. The efficiency difference between using @ and not using @ is: 3 times.
Especially do not use @ in a loop. In the test of 5 loops, even if you use error_reporting(0) to turn off the error first and then turn it on after the loop is completed, it is faster than using @.
Make good use of strncmp
When you need to compare whether the "first n characters" are the same, use strncmp/strncasecmp instead of substr/strtolower, let alone PCRE. Don't even mention ereg. strncmp/strncasecmp is the most efficient (although not much higher).
Use substr_compare with caution (PHP5 ONLY)
According to the above reason, substr_compare should be faster than substr first and then. The answer is no, unless:
- Case-insensitive comparison
- Compare larger strings
Don’t use constants instead of strings
Why:
- Need to query the hash table twice
- Need to convert the constant name to lowercase (for the second query time)
- Generate E_NOTICE warning
- Will create a temporary string
Efficiency difference: 700%.
Don’t put count/strlen/sizeof in the conditional statement of the for loop
Tips: My personal approach
for ($i = 0, $max = count($array);$i ?>
The efficiency improvement is relative to :
- count 50%
- strlen 75%
Short code is not necessarily fast
//longest
if ($a == $b) {
$str .= $a;
} else {
$str .= $b;
}
// longer
if ($a == $b) {
$str .= $a;
}
$str .= $b;
// short
$str .= ($a == $b ? $a : $b);
?>
Which one do you think is faster?
Efficiency comparison:
- longest: 4.27
- longer: 4.43
- short: 4.76
Incredible? One more one:
// original
$d = dir('.');
while (($entry = $d->read ()) !== false) {
if ($entry == '.' || $entry == '..') {
continue;
}
}
/ / versus
glob('./*');
// versus (include . and ..)
scandir('.');
?>
Which one is faster?
Efficiency comparison:
- original: 3.37
- glob: 6.28
- scandir: 3.42
- original without OO: 3.14
- SPL (PHP5): 3.95
Voiceover: From now on, it can be seen that the object-oriented efficiency of PHP5 has been improved a lot, and the efficiency is not much different from that of pure functions.
Improve PHP file access efficiency
When you need to include other PHP files, use full paths, or relative paths that are easy to convert.
include 'file.php'; // bad approach
include './file.php'; // good
include '/path/to/file .php'; // ideal
?>
Make the best use of everything
PHP has many extensions and functions available. Before implementing a function, you should take a look Does PHP have this function? Is there a simpler implementation?
$filename = "./somepic.gif";
$handle = fopen($filename, "rb");
$contents = fread($handle , filesize($filename));
fclose($handle);
// vs. much simpler
file_get_contents('./somepic.gif');
?>
Tips about references
References can:
- Simplify access to complex structured data
- Optimize memory Use
$a['b']['c'] = array();
// slow 2 extra hash lookups per access
for ($i = 0; $i $a['b']['c'][$i] = $i;
// much faster reference based approach
$ref =& $a['b']['c'];
for ($i = 0; $i $ref[$i] = $i;
?>
$a = 'large string';
// memory intensive approach
function a($str){
return $str.'something';
}
// more efficient solution
function a(&$str){
$str .= 'something';
}
?> ;
========================================== ======
Reference materials
http://ilia.ws
Ilia’s personal website, Blog, the development he participated in and some publications he published Links and more.
http://ez.no
eZ components official website, eZ comp is an open source universal library for PHP5, taking efficiency as its own responsibility, and Ilia also participated in the development.
http://phparch.com
php|architect, a good php publisher/training organization. If you can't afford it or can't buy it, there are many pirated copies of classics available online.
http://talks.php.net
The collection of speeches at the PHP conference is not very rich yet, but the content is all good stuff that makes people forget to eat and sleep easily. It is recommended to study it carefully in the morning when you are sleepy or after lunch, otherwise you will forget to eat and sleep!

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

php判断有没有小数点的方法:1、使用“strpos(数字字符串,'.')”语法,如果返回小数点在字符串中第一次出现的位置,则有小数点;2、使用“strrpos(数字字符串,'.')”语句,如果返回小数点在字符串中最后一次出现的位置,则有。

方法:1、用“str_replace(" ","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\ \;||\xc2\xa0)/","其他字符",$str)”语句。

在PHP中,可以利用implode()函数的第一个参数来设置没有分隔符,该函数的第一个参数用于规定数组元素之间放置的内容,默认是空字符串,也可将第一个参数设置为空,语法为“implode(数组)”或者“implode("",数组)”。

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。


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

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

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

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download
The most popular open source editor
