Home php教程 php手册 php性能优化

php性能优化

Jun 06, 2016 am 09:52 AM
php code Open source Performance optimization programming programming language software development

 
  很长时间没有写博文了,最近换了工作,长时间加班,根本没有时间做其他事情!今天闲下来了,想一想php性能方面的事情。这也是我2014年的第一篇博文!
  推荐阅读:初学者到中级者应该掌握的!
 
  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属性。
 
 
class dog {
  public $name = '';

  public function setName($name) {
    $this->name = $name;
  }

  public function getName() {
    return $this->name;
  }
}
Copy after login

  

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

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

  

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

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

  

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

  

上面的代码没有任何原因,复制了一遍变量。你仅需要使用内联的方式简单输出变量,而不用额外的消耗内存。
 
echo strip_tags($_POST['description']);
Copy after login

  

 

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

  过程:

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

  

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

$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

  过程:

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

Video Face Swap

Video Face Swap

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

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
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)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP's Purpose: Building Dynamic Websites PHP's Purpose: Building Dynamic Websites Apr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP: Handling Databases and Server-Side Logic PHP: Handling Databases and Server-Side Logic Apr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Why Use PHP? Advantages and Benefits Explained Why Use PHP? Advantages and Benefits Explained Apr 16, 2025 am 12:16 AM

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP vs. Python: Use Cases and Applications PHP vs. Python: Use Cases and Applications Apr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

See all articles