PHP 性能优化

Jun 20, 2016 pm 12:45 PM
php performance optimization

原文出处: 川山甲 

php是一个很流行的脚本语言,现在很多公司(新浪、优酷、百度、搜狐、淘宝等等)在使用这种语言进行网站开发。我的这篇文章,我只是希望能够提高你的php脚本性能。请记住你的php脚本性能,很多时候依赖于你的php版本、你的web server环境和你的代码的复杂度。

优化你代码中的瓶颈

Hoare曾经说过“过早优化是一切不幸的根源”。当你想要让你的网站更快运转的时候,你才应该去做优化的事情。当你要改变你代码之前,你需要做的事是什么原因引起了系统缓慢?你可以通过以下指导和其他方式优化你的php,可能是数据库原因也可能是网路原因!通过优化你的php代码,你能尝试着找出你的系统瓶颈。

升级你的php版本

你的团队成员提出,这些年php引擎已经有很多象征性的性能提升。如果你的web server仍然运行着比较老的版本,如php3或者php4。那么在你尝试着优化你代码之前,应该先深入调查一下版本之间的升级情况。

点击以下链接,可以了解具体细节:

从 PHP 4 移植到 PHP 5
从 PHP 5.0.x 移植到 PHP 5.1.x
从 PHP 5.1.x 移植到 PHP 5.2.x

使用缓存

利用缓存模块(如Memcache)或者模板系统(如Smarty)进行缓存处理。我们可以缓存数据库结果和提取页面结果的方式来提升网站性能。

使用输出缓冲区

当你的脚本尝试着渲染的时候,php会使用内存缓存区保存所有的数据。缓存区可能让你的页面看起来很慢,原因是缓冲区填满所有要响应的数据之后再把结果响应给用户。幸运的是,你能够做一下改变,迫使php强行在缓冲区填满之前把数据响应给用户,这样就会让你的网站看起来更快一些。

  • 输出缓存控制

避免写幼稚的setters和getters

当你写php类的时候,你可以直接操作对象属性,这样能帮助你节省时间和提升你的脚本性能。而不是那种让人感到幼稚可笑的setters和getters。

下面是一些案例:dog类通过使用setName()和getName()方式来操作name属性。

1

class dog {  public $name = ''public function setName($name) {    $this->name = $name;  }  public function getName() {    return $this->name;  }}

Copy after login

注意:setName()和getName()除了存储和返回name属性外,没做任何工作。

1

$rover = new dog();$rover->setName('rover');echo $rover->getName();

Copy after login

直接设置和访问name属性,性能能提升100%,而且也能缩减开发时间!

1

$rover = new dog();$rover->name = 'rover';echo $rover->name;

Copy after login

没有原因不要copy变量

有时初级phper,为了使代码更加“干净”,常常把已经定义的变量重新赋值给另一个变量。这实际上就导致了双重内存的消耗(当改变变量的时候),这就导致脚本的性能下降。比如一个用户把一个512KB的变量在额外插入给另一个变量,那么就会导致1MB的内存被消耗掉。

1

$description = strip_tags($_POST['description']);echo $description;

Copy after login

上面的代码没有任何原因,复制了一遍变量。你仅需要使用内联的方式简单输出变量,而不用额外的消耗内存。

1

echo strip_tags($_POST['description']);

Copy after login

避免循环做SQL操作

经常犯的错误是把一个SQL 操作放置到一个循环中,这就导致频繁的访问数据库,更重要的是,这会直接导致脚本的性能低下。以下的例子,你能够把一个循环操作重置为一个单一的SQL语句。

1

foreach ($userList as $user) {  $query = 'INSERT INTO users (first_name,last_name) VALUES("' . $user['first_name'] . '", "' . $user['last_name'] . '")';  mysql_query($query);}

Copy after login

过程:

1

INSERT INTO users (first_name,last_name) VALUES("John", "Doe")

Copy after login

替换这种循环方案,你能够拼接数据成为一个单一的数据库操作。

1

$userData = array();foreach ($userList as $user) {    $userData[] = '("' . $user['first_name'] . '", "' . $user['last_name'] . '")'; }$query = 'INSERT INTO users (first_name,last_name) VALUES' . implode(',', $userData);mysql_query($query);

Copy after login

过程:

1

INSERT INTO users (first_name,last_name) VALUES("John", "Doe"),("Jane", "Doe")...

Copy after login
  • MySQL INSERT Syntax

其他资源

  • PHP Memcache module
  • Smarty templating engine
  • http://3v4l.org ? 分析各个版本间的代码执行效率,非常不错的网站
  • http://www.php-internals.com/ ???研究php内核的网站!

总结

php在性能方面的优化还有很多,如果对这方面有更深入了解的人,可以一起探讨,我会把大家好的建议也放入到博文里面, 供其他phper参考。作为phper能提高众多phper
的能力是一件非常自豪的事情。??很多人都把php当成草根语言,我个人也希望php语言将来能走的更远,这样作为phper手中的money也会越来越多!

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

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

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)

Working with Flash Session Data in Laravel Working with Flash Session Data in Laravel Mar 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 APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 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 Analysis PHP Logging: Best Practices for PHP Log Analysis Mar 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 Tests Simplified HTTP Response Mocking in Laravel Tests Mar 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 CodeCanyon 12 Best PHP Chat Scripts on CodeCanyon Mar 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