php中优化建义与优化代码
文章总结了关于php中优化建义与优化代码,给php程序员有很好的建义
1、如果能将类的方法定义成static,就尽量定义成static,它的速度会提升将近4倍.
2、$row["id"] 的速度是$row[id]的7倍.
3、echo 比 print 快,并且使用echo的多重参数(译注:指用逗号而不是句点)代替字符串连接,比如echo $str1,$str2.
4、在执行for循环之前确定最大循环数,不要每循环一次都计算最大值,最好运用foreach代替.
5、注销那些不用的变量尤其是大数组,以便释放内存.
6、尽量避免使用__get,__set,__autoload.
7、require_once()代价昂贵.
8、include文件时尽量使用绝对路径,因为它避免了PHP去include_path里查找文件的速度,解析操作系统路径所需的时间会更少.
9、如果你想知道脚本开始执行(译注:即服务器端收到客户端请求)的时刻,使用$_SERVER["REQUEST_TIME"]要好于 time().
10、函数代替正则表达式完成相同功能.
11、str_replace函数比preg_replace函数快,但strtr函数的效率是str_replace函数的四倍.
12、如果一个字符串替换函数,可接受数组或字符作为参数,并且参数长度不太长,那么可以考虑额外写一段替换代码,使得每次传递参数是一个字符,而不是只写一行代码接受数组作为查询和替换的参数.
13、使用选择分支语句(译注:即switch case)好于使用多个if,else if语句.
14、用@屏蔽错误消息的做法非常低效,极其低效.
15、打开apache的mod_deflate模块,可以提高网页的浏览速度.
16、数据库连接当使用完毕时应关掉,不要用长连接.
17、错误消息代价昂贵.
18、在方法中递增局部变量,速度是最快的.几乎与在函数中调用局部变量的速度相当.
19、递增一个全局变量要比递增一个局部变量慢2倍.
20、递增一个对象属性(如:$this->prop++)要比递增一个局部变量慢3倍.
21、递增一个未预定义的局部变量要比递增一个预定义的局部变量慢9至10倍.
22、仅定义一个局部变量而没在函数中调用它,同样会减慢速度(其程度相当于递增一个局部变量).PHP大概会检查看是否存在全局变量.
23、方法调用看来与类中定义的方法的数量无关,因为我(在测试方法之前和之后都)添加了10个方法,但性能上没有变化.
24、派生类中的方法运行起来要快于在基类中定义的同样的方法.
25、调用带有一个参数的空函数,其花费的时间相当于执行7至8次的局部变量递增操作.类似的方法调用所花费的时间接近于15次的局部变量递增操作.
26、Apache解析一个PHP脚本的时间要比解析一个静态HTML页面慢2至10倍.尽量多用静态HTML页面,少用脚本.
27、除非脚本可以缓存,否则每次调用时都会重新编译一次.引入一套PHP缓存机制通常可以提升25%至100%的性能,以免除编译开销.
28、尽量做缓存,可使用memcached.memcached是一款高性能的内存对象缓存系统,可用来加速动态Web应用程序,减轻数据库负载.对运算码 (OP code)的缓存很有用,使得脚本不必为每个请求做重新编译.
29、当操作字符串并需要检验其长度是否满足某种要求时,你想当然地会使用strlen()函数.此函数执行起来相当快,因为它不做任何计算,只返回在zval 结构(C的内置数据结构,用于存储PHP变量)中存储的已知字符串长度.但是,由于strlen()是函数,多多少少会有些慢,因为函数调用会经过诸多步骤,如字母小写化(译注:指函数名小写化,PHP不区分函数名大小写)、哈希查找,会跟随被调用的函数一起执行.在某些情况下,你可以使用isset() 技巧加速执行你的代码.
(举例如下)
if (strlen($foo)
(与下面的技巧做比较)
if (!isset($foo{5})) { echo “Foo is too short”$$ }
调用isset()恰巧比strlen()快,因为与后者不同的是,isset()作为一种语言结构,意味着它的执行不需要函数查找和字母小写化.也就是说,实际上在检验字符串长度的顶层代码中你没有花太多开销.
34、当执行变量$i的递增或递减时,$i++会比++$i慢一些.这种差异是PHP特有的,并不适用于其他语言,所以请不要修改你的C或Java 代码并指望它们能立即变快,没用的.++$i更快是因为它只需要3条指令(opcodes),$i++则需要4条指令.后置递增实际上会产生一个临时变量,这个临时变量随后被递增.而前置递增直接在原值上递增.这是最优化处理的一种,正如Zend的PHP优化器所作的那样.牢记这个优化处理不失为一个好主意,因为并不是所有的指令优化器都会做同样的优化处理,并且存在大量没有装配指令优化器的互联网服务提供商(ISPs)和服务器.
35、并不是事必面向对象(OOP),面向对象往往开销很大,每个方法和对象调用都会消耗很多内存.
36、并非要用类实现所有的数据结构,数组也很有用.
37、不要把方法细分得过多,仔细想想你真正打算重用的是哪些代码?
38、当你需要时,你总能把代码分解成方法.
39、尽量采用大量的PHP内置函数.
40、如果在代码中存在大量耗时的函数,你可以考虑用C扩展的方式实现它们.
41、评估检验(profile)你的代码.检验器会告诉你,代码的哪些部分消耗了多少时间.Xdebug调试器包含了检验程序,评估检验总体上可以显示出代码的瓶颈.
42、mod_zip可作为Apache模块,用来即时压缩你的数据,并可让数据传输量降低80%.
43、在可以用file_get_contents替代file、fopen、feof、fgets等系列方法的情况下,尽量用 file_get_contents,因为他的效率高得多!但是要注意file_get_contents在打开一个URL文件时候的PHP版本问题;
44、尽量的少进行文件操作,虽然PHP的文件操作效率也不低的;
45、优化 Select SQL 语句,在可能的情况下尽量少的进行 Insert、Update 操作(在 update 上,我被恶批过);
46、尽可能的使用PHP内部函数(但是我却为了找个 PHP 里面不存在的函数,浪费了本可以写出一个自定义函数的时间,经验问题啊!);
47、循环内部不要声明变量,尤其是大变量:对象(这好像不只是PHP里面要注意的问题吧?)
48、多维数组尽量不要循环嵌套赋值
49、在可以用PHP内部字符串操作函数的情况下,不要用正则表达式
50、foreach 效率更高,尽量用 foreach 代替 while 和 for 循环
51、用单引号替代双引号引用字符串
52、用i+=1代替i=i+1.符合c/c++的习惯,效率还高
53、对 global 变量,应该用完就 unset( )掉
代码优化实例
在函数中,传递数组时
使用 return 比使用 global 要高效
比如
<?php function userloginfo($usertemp) { $detail = explode("|", $usertemp); return $detail; } $login = userloginfo($userdb); ?>
比
<?php function userloginfo($usertemp) { global $detail; $detail = explode("|", $usertemp); } userloginfo($userdb); ?>
要高效
2,(这个代码用于得到程序目录对应的网址,推荐使用)
$urlarray=explode("/",$HTTP_SERVER_VARS["REQUEST_URI"]); $urlcount=count($urlarray);unset($urlarray[$urlcount-1]); $ofstarurl="http://".$HTTP_SERVER_VARS["HTTP_HOST"].implode("/",$urlarray);
这段代码比
$pre_urlarray=explode("/",$HTTP_SERVER_VARS["HTTP_REFERER"]); $pre_url=array_pop($pre_urlarray);
要高效
3,在循环中判断时,数值判断使用恒等要比等于高效
$a=2;$b=2;
比如
if($a==$b)$c=$a;
比
if($a===$b)$c=$a;
高效
4,mysql 查询时尽量使用where in 少用 limit
limit查多记录的前几条, 速度很快, 但是查询最面几条就会慢
使用in .在查询连续性记录,非常快, 非连续性记录第一次运行会稍微慢一点,但是之后将比较快!
5,NT服务器数据操作稳定性不及unix/linux
6,输出前使用尽量使用 ob_start(); 可以加快输出速度,适用NT或nuli/linux,对unlix类服务器 如果使用 ob_start("ob_gzhandler");输出效率将更高
7,判断的时候尽量使用if($a==他的值) 否定的时候尽量使用if(empty($a)),因为这样程序运行更快速
8,使用不等时 != 与 <> 效率相当
9,个人经验得 使用 $a="11111111111111"; 的效率和 $a="11111111111111"; 相当.并不象书本说的相差很大
10,使用规范的SQL语句, 会有利于MySQL的解析
11,使用
实例代码如下:
<?php if ($online) { $online1 = $online; setcookie("online1", $online, $cookietime, $ckpath, $ckdomain, $secure); } ?>
COOKIE将马上生效使用
if($online)
setcookie("online1",$online,$cookietime,$ckpath,$ckdomain,$secure);
COOKIE需要再刷新一次才能生效
12,使用
实例代码如下:
<?php $handle = fopen($filename, wb); flock($handle, LOCK_SH); $filedata = fread($handle, filesize($filename)); fclose($handle); ?>
比
file($filename);
无论在速度还是稳定上都要优秀
13,截断字符串优化函数(可避免?字符出现)
实例代码如下:
<?php function substrs($content, $length) { if (strlen($content) > $length) { $num = 0; for ($i = 0; $i < $length - 3; $i++) { if (ord($content[$i]) > 127) $num++; } $num % 2 == 1 ? $content = substr($content, 0, $length - 4) : $content = substr($content, 0, $length - 3); $content.= "..."; } return $content; } ?>
比如$newarray[1]=substrs($newarray[1],25);
14,程序中屏蔽大小写
实例代码如下:
<?php for ($asc = 65; $asc <= 90; $asc++) { //strtolower() 此函数在一些服务器会产生乱码! if (strrpos($regname, chr($asc)) !== false) { $error = "为了避免用户名混乱,用户名中禁止使用大写字母,请使用小写字母"; $reg_check = 0; } } ?>
15,不使用 file();和不使用 fget();(不稳定或速度慢) 取一数组函数
实例代码如下:
<?php function openfile($filename, $method = "rb") { $handle = @fopen($filename, $method); @flock($handle, LOCK_SH); @$filedata = fread($handle, filesize($filename)); @fclose($handle); $filedata = str_replace(" ", " <ofstar:>", $filedata); $filedb = explode("<ofstar:>", $filedata); //array_pop($filedb); $count = count($filedb); if ($filedb[$count-1] == ''){unset($filedb[$count - 1]);} return $filedb; } ?>
//这个函数虽然代码比较多,不过在速度和稳定性上优势很大!
实现如上数组分离代码
这样后,访问tempArray的块数据就非常方便了
实例代码如下:
<?php foreach($tempArray as $row){ array1[$row['ID']] = $row['Key']; array2[$row['Key']][] = $row; } ?>
访问和处理代码
实例代码如下:
<?php foreach($array1 as $ID => $Key){ $this->doSomeThing($ID); //访问tempArray的块数组$array2[$Key] $this->doSomeThing2($array2[$Key]); } ?>
永久链接:
转载随意!带上文章地址吧。

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

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



C++ is a high-performance programming language that provides developers with flexibility and scalability. Especially in large-scale data processing scenarios, the efficiency and fast computing speed of C++ are very important. This article will introduce some techniques for optimizing C++ code to cope with large-scale data processing needs. Using STL containers instead of traditional arrays In C++ programming, arrays are one of the commonly used data structures. However, in large-scale data processing, using STL containers, such as vector, deque, list, set, etc., can be more

As Python becomes more and more popular, more and more people are using Python to develop software and applications. However, during the development process of Python code, code redundancy problems are often encountered. This article will introduce how to solve Python's code redundancy errors. What are Python code redundancy errors? Python code redundancy errors refer to the existence of redundant, repetitive, useless or redundant codes in the code. These codes not only increase the complexity and code volume of the program, but also reduce the readability of the code.

How to improve the efficiency and quality of Java development projects In the current rapid development environment of software development, Java, as a powerful programming language, is widely used in various project development. However, many Java developers encounter problems of low efficiency and low quality during project development. In order to solve these problems, this article will introduce some methods and techniques to help developers improve the efficiency and quality of Java projects. 1. Reasonably plan the project structure and module division. A good project structure and module division are the key to improving project efficiency and quality.

In-depth understanding of the underlying development principles of PHP: Sharing practical code optimization and performance debugging skills Introduction: PHP is a scripting language widely used in web development, and an in-depth understanding of its underlying development principles is very important for developers. Only with sufficient understanding of the underlying principles of PHP can we write efficient and optimized code and quickly locate and solve performance problems. This article will share some practical experience in optimizing code and performance debugging, and attach specific code examples. 1. Optimize the code. Optimizing the code is to improve P

Optimizing code calling logic: Tips for mastering GolangFacade pattern Introduction: In the process of software development, we often encounter situations where code calling logic is complex. This not only makes it difficult to maintain and extend the code, but also makes the code difficult to understand and reuse. For this purpose, adopting good design patterns is a good choice. This article will introduce a design pattern in Golang - Facade mode, and how to use Facade mode to optimize the calling logic of the code. Help readers through specific code examples

When writing code in the Go language, if-else statements are often used to make conditional judgments. However, in some cases, we can optimize the code structure and remove the else keyword to make the code more concise and readable. Here are some specific examples of other optimization techniques for removing else. Example 1: Use if to directly return funcisPositive(numint)bool{ifnum>=0{retur

A deep dive into Python’s caching mechanism: the key to optimizing code execution speed Introduction: Python is a widely used high-level programming language loved by many developers. However, Python's execution speed is often questioned compared to other programming languages. In order to solve this problem, Python introduced a caching mechanism to improve code execution efficiency. This article will delve into Python's caching mechanism and provide specific code examples to help developers better understand and apply this key optimization technology. one

Free your hands! PyCharm batch comment skills help you quickly optimize code Introduction: In daily programming work, we often need to process a large number of code comments. Manually commenting code line by line is not only time-consuming and labor-intensive, but also error-prone. In order to improve programming efficiency, let's take a look at the batch comment technique in PyCharm, which can help you quickly optimize your code. This article will introduce you to the batch annotation function in PyCharm in detail through specific code examples. 1. Basic usage of PyCharm batch annotation PyC
