search
HomeBackend DevelopmentPHP Tutorial40条优化php代码的小范例

40条优化php代码的小实例


1.如果一个方法能被静态,那就声明他为静态的,速度可提高1/4;

2.echo的效率高于print,因为echo没有返回值,print返回一个整型;

3.在循环之前设置循环的最大次数,而非在在循环中;

4.销毁变量去释放内存,特别是大的数组;

5.避免使用像__get, __set, __autoload等魔术方法;

6.requiere_once()比较耗资源;

7.在includes和requires中使用绝对路径,这样在分析路径花的时间更少;

8.如果你需要得sexinsex到脚本执行时的时间,$_SERVER['REQUSET_TIME']优于time();

9.能使用字符处理函数的,尽量用他们,因为效率高于正则;

10.str_replace字符替换比正则替换preg_replace快,但strtr比str_replace又快1/4;

11.如果一个函数既能接受数组又能接受简单字符做为参数,例如字符替换,并且参数列表不是太长,可以考虑多用一些简洁的替换语句,一次只替换一个字符,而不是接受数组做为查找和替换参数。大事化小,1+1>2;

[email protected];

13.$row['id']比$row[id]速度快7倍,建议养成数组键加引号的习惯;

14.错误信息很有用;

15.在循环里别用函数,例如For($x=0; $x
16.在方法里建立局部变量速度最快,97xxoo几乎和在方法里调用局部变量一样快;

17.建立一个全局变量要比局部变量要慢2倍;

18.建立一个对象属性(类里面的变量)例如($this->prop++)比局部变量要慢3倍;

19.建立一个未声明的局部变量要比一个初始化的局部变量慢9-10倍;

20.声明一个未被任何一个函数使用过的全局变量也会使性能降低(和声明相同数量的局部变量一样),PHP可能去检查这个全局变量是否存在;

21.方法的性能和在一个类里面定义的方法的数目没有关系,因为我添加10个或多个方法到测试的类里面(这些方法在测试方法的前后)后性能没什么差异;

22.在子类里方法的性能优于在基类中;

23.只调用一个参数并且函数体为空的函数运行花费的时间等于7-8次$localvar++运算,而一个类似的方法(类里的函数)运行等于大约15次$localvar++运算;

24.Surrounding your string by ‘ instead of ” will make things interpret a little faster since php looks for variables inside “…” but not inside ‘…’. Of course you can only do this when you don’t need to have variables in the string.

25.当输出字符串时用逗号代替点分割更快些。注意:这只对echo起作用,这个函数能接受一些字符串作为参数;

26.在apache服务器里一个php脚本页面比相应的HTML静态页面生成至少要多花2-10倍的时间,建议多用些静态HTML页面和少量的脚步;

27.除非你的安装了缓存,不然你的php脚本每次被访问都需要被重编译。建议安装个php缓存程序,这样通过去除一些重复的编译来很明显的提高你20-100%的性能;

28.建议用memcached,高性能的分布式内存对象缓存系统,提高动态网络应用程序性能,减轻数据库的负担;

29.使用ip2long()和long2ip()函数把IP地址转成整型存放进数据库而非字符型。这几乎能降低1/4的存储空间。同时可以很容易对地址进行排序和快速查找;

30.使用checkdnsrr()通过域名存在性来确认部分email地址的有效性,这个内置函数能保证每一个的域名对应一个IP地址;

31.如果你在使用php5和mysql4.1以上的版本,考虑使用mysql_*的改良函数mysqli_*;

32.试着喜欢使用三元运算符(?:);

33.在你想在彻底重做你的项目前,看看PEAR有没有你需要的。PEAR是个巨大的资源库,很多php开发者都知道;

34.使用highlight_file()能自动打印一份很好格式化的页面源代码的副本;

35.使用error_reporting(0)函数来预防潜在的敏感信息显示给用户。理想的错误报告应该被完全禁用在php.ini文件里。可是如果你在用一个共享的虚拟主机,php.ini你不能修改,那么你最好添加error_reporting(0)函数,放在每个脚本文件的第一行(或用require_once()来加载)这能有效的保护敏感的SQL查询和路径在出错时不被显示;

36.使用 gzcompress() 和gzuncompress()对容量大的字符串进行压缩(解压)在存进(取出)数据库时。这种内置的函数使用gzip算法能压缩到90%;

37.通过参数变量地址得引用来使一个函数有多个返回值。你可以在变量前加个“&”来表示按地址传递而非按值传递;

38.Fully understand “magic quotes” and the dangers of SQL injection. I’m hoping that most developers reading this are already familiar with SQL injection. However, I list it here because it’s absolutely critical to understand. If you’ve never heard the term before, spend the entire rest of the day googling and reading.

39.使用strlen()因为要调用一些其他操作例如lowercase和hash表查询所以速度不是太好,我们可以用isset()来实现相似的功能,isset()速度优于strlen();

40.When incrementing or decrementing the value of the variable $i++ happens to be a tad slower then ++$i. This is something PHP specific and does not apply to other languages, so don’t go modifying your C or Java code thinking it’ll suddenly become faster, it won’t. ++$i happens to be faster in PHP because instead of 4 opcodes used for $i++ you only need 3. Post incrementation actually causes in the creation of a temporary var that is then incremented. While pre-incrementation increases the original value directly. This is one of the optimization that opcode optimized like Zend’s PHP optimizer. It is a still a good idea to keep in mind since not all opcode optimizers perform this optimization and there are plenty of ISPs and servers running without an opcode optimizer.

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
How can you prevent session fixation attacks?How can you prevent session fixation attacks?Apr 28, 2025 am 12:25 AM

Effective methods to prevent session fixed attacks include: 1. Regenerate the session ID after the user logs in; 2. Use a secure session ID generation algorithm; 3. Implement the session timeout mechanism; 4. Encrypt session data using HTTPS. These measures can ensure that the application is indestructible when facing session fixed attacks.

How do you implement sessionless authentication?How do you implement sessionless authentication?Apr 28, 2025 am 12:24 AM

Implementing session-free authentication can be achieved by using JSONWebTokens (JWT), a token-based authentication system where all necessary information is stored in the token without server-side session storage. 1) Use JWT to generate and verify tokens, 2) Ensure that HTTPS is used to prevent tokens from being intercepted, 3) Securely store tokens on the client side, 4) Verify tokens on the server side to prevent tampering, 5) Implement token revocation mechanisms, such as using short-term access tokens and long-term refresh tokens.

What are some common security risks associated with PHP sessions?What are some common security risks associated with PHP sessions?Apr 28, 2025 am 12:24 AM

The security risks of PHP sessions mainly include session hijacking, session fixation, session prediction and session poisoning. 1. Session hijacking can be prevented by using HTTPS and protecting cookies. 2. Session fixation can be avoided by regenerating the session ID before the user logs in. 3. Session prediction needs to ensure the randomness and unpredictability of session IDs. 4. Session poisoning can be prevented by verifying and filtering session data.

How do you destroy a PHP session?How do you destroy a PHP session?Apr 28, 2025 am 12:16 AM

To destroy a PHP session, you need to start the session first, then clear the data and destroy the session file. 1. Use session_start() to start the session. 2. Use session_unset() to clear the session data. 3. Finally, use session_destroy() to destroy the session file to ensure data security and resource release.

How can you change the default session save path in PHP?How can you change the default session save path in PHP?Apr 28, 2025 am 12:12 AM

How to change the default session saving path of PHP? It can be achieved through the following steps: use session_save_path('/var/www/sessions');session_start(); in PHP scripts to set the session saving path. Set session.save_path="/var/www/sessions" in the php.ini file to change the session saving path globally. Use Memcached or Redis to store session data, such as ini_set('session.save_handler','memcached'); ini_set(

How do you modify data stored in a PHP session?How do you modify data stored in a PHP session?Apr 27, 2025 am 12:23 AM

TomodifydatainaPHPsession,startthesessionwithsession_start(),thenuse$_SESSIONtoset,modify,orremovevariables.1)Startthesession.2)Setormodifysessionvariablesusing$_SESSION.3)Removevariableswithunset().4)Clearallvariableswithsession_unset().5)Destroythe

Give an example of storing an array in a PHP session.Give an example of storing an array in a PHP session.Apr 27, 2025 am 12:20 AM

Arrays can be stored in PHP sessions. 1. Start the session and use session_start(). 2. Create an array and store it in $_SESSION. 3. Retrieve the array through $_SESSION. 4. Optimize session data to improve performance.

How does garbage collection work for PHP sessions?How does garbage collection work for PHP sessions?Apr 27, 2025 am 12:19 AM

PHP session garbage collection is triggered through a probability mechanism to clean up expired session data. 1) Set the trigger probability and session life cycle in the configuration file; 2) You can use cron tasks to optimize high-load applications; 3) You need to balance the garbage collection frequency and performance to avoid data loss.

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

Video Face Swap

Video Face Swap

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

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

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

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment