Improve performace: check your loops

本文探讨了如何通过检查和优化循环来提升PHP应用程序的性能。介绍了几种工具帮助定位性能瓶颈,并提供了具体示例说明如何重构循环内的代码以提高效率。
 

Improve performace: check your loops

Before I start
I’ve always stayed away from writing a performance topic. There seems to be a lot of performance enthusiasts, benchmarking anything they can, in order to scoop off a few more percent of performance time. To my opinion, if your system is already reacting within an acceptable fashion, there is no need to try to further improve performance. Maintainability is a much more important topic to look at, at that point.

Finding out what is the problem
So you have a script which is not performing the way you want to. The first thing you should do it try to find out what the problem is. There are some tools out there that can help you. If you’re using Zend Studio, there is a profiler which shows you a tree of files and functions with the amount of processing time. (Warning: With Zend Studio 5, you need to close your project and all open files, otherwise you’ll get incorrect values). There is also a profiler in XDebug, which is a bit harder to set up, but works just as well (or even a bit better actually).

If you don’t have the option to install any of these tools, you can echo (or use FirePHP to output) the execution times, using the following script:

 

Improve performace: check your loops

Before I start
I’ve always stayed away from writing a performance topic. There seems to be a lot of performance enthusiasts, benchmarking anything they can, in order to scoop off a few more percent of performance time. To my opinion, if your system is already reacting within an acceptable fashion, there is no need to try to further improve performance. Maintainability is a much more important topic to look at, at that point.

Finding out what is the problem
So you have a script which is not performing the way you want to. The first thing you should do it try to find out what the problem is. There are some tools out there that can help you. If you’re using Zend Studio, there is a profiler which shows you a tree of files and functions with the amount of processing time. (Warning: With Zend Studio 5, you need to close your project and all open files, otherwise you’ll get incorrect values). There is also a profiler in XDebug, which is a bit harder to set up, but works just as well (or even a bit better actually).

If you don’t have the option to install any of these tools, you can echo (or use FirePHP to output) the execution times, using the following script:

___FCKpd___0

Most likely the problem will be one of these three (in order of likeliness):

  1. A slow database query. Solving this is outside the scope of this article, but read this PDF about Query tuning for starters.
  2. To much is executed within a loop and/or the number of items for the loop is to big. Read the rest of the article.
  3. To much code is executed. This is probably cause of an abstraction layer that is simply to big or of to many abstraction layers. Try to do some refactoring, removing unnecessary abstraction or bypass abstraction on bottleneck positions.

Get the data ready before going into the loop
Looping through a large list in PHP can be very expensive performance wise, even if code in the loop is limited. If you’re looping through a mysql result, see if you can get the data as you want to use it from the query by using string, date and numeric functions and things like GROUP_CONCAT. Also try not to have to filter the data in PHP, you should only get the rows out the DB you actually need.

Don’t do things in the loop, you can also do outside it
Try to do as much stuff as possible outside of the loop. If an operation gives the same result for each item, you can surely put is outside of the loop.

Don’t do this:

for ($i=0; $i<sizeof($array); $i++) {
  if ($mark) {
     list($pre, $post) = explode('~', $tpl, 2);
     echo $pre, $array[$i]['desc'], $post; 
  } else {
     echo " - ", $array[$i]['desc'];
  }
}

Instead do this:

if ($mark) {
  list($pre, $post) = explode('~', $tpl, 2);
} else {
  $pre = " - ";
  $post = "";
}
 
for ($i=0, $n=sizeof($array); $i<$n; $i++) {
   echo $pre, $array[$i]['desc'], $post; 
}

Use create_function to aid you
Sometimes you know you should put things outside of the loop, however the logic is so complex it can only be done in code. In that case you can use create_function together with array_map to help you out.

Don’t do this:

echo "<table>";
foreach ($rows as $row) {
  echo "<tr>";
  foreach ($fields as $field) {
    echo "<td>";
    switch ($field['type']) {
      case 'website': echo "<a href=/"http://", $row[$field['name']], "/">", $row[$field['name']], "</a>"; break;
      case 'email': echo "<a href=/"mailto:", $row[$field['name']], "/">", $row[$field['name']], "</a>"; break;
      case 'currency': echo "€ ", number_format($row[$field['name']], 2, ',', '.'); break; // Dutch notation
      default: echo $row[$field['name']];
    }
    echo "</td>";
  }
  echo "</tr>";
}
echo "</table>";

Instead do this:

$code = 'echo "<tr>"';
foreach ($fields as $field) {
  $code .= ', "<td>"';
  switch ($field['type']) {
      case 'website': $code .= ', "<a href=//"http://", $row["' . $field['name'] . '"], "//">", $row["' . $field['name'] . '"], "</a>"'; break;
      case 'email': $code .= ', "<a href=//"mailto:", $row["' . $field['name'] . '"], "//">", $row["' . $field['name'] . '"], "</a>"'; break;
      case 'currency': $code .= ', "€ ", number_format($row["' . $field['name'] . '"], 2, ',', '.')'; break; // Dutch notation
      default: $code .= ', $row["' . $field['name'] '"]';
  }
  $code .= ', "</td>"';
}
$code = ', "</tr>";';
 
echo "<table>";
array_walk($rows, create_function('$row', $code));
echo "</table>";

Be careful with abstraction in loops
Things like iterators and overloading (__get/__set) are a lot slower than normal loops and getting and setting properties. When you have a lot of data it is probably better to stay a way of these kind of abstractions, especially if you only use them to make you code more pretty.
Also your own abstraction might be dangerous. The less code that is performed in a loop with lots of data, the better.

Sometimes you can prevent loops altogether
With PHP functions like join, array_sum and array_reduce and MySQL functions like GROUP_CONCAT, you may sometimes get out of using a PHP loop.

if (!empty($categories)) $db->query("INSERT INTO product_category (product_id, category_id) VALUES ($prod_id, " . join("), ($prod_id, ", $categories) . ")");

Last resort: write an extension
If you have a piece of code in a loop which simply can not be written differently, but is causing mayor performance issues, see if you can rewrite that in C. Compiled code is simply a lot faster and will most likely solve your problem. The syntax of C is much like PHP, though there are a lot of gotcha’s. You can turn that C code into a PHP extension, so you can use it in your application. I’ve used the following articles to get started with PHP extensions:
Extension Writing Part I: Introduction to PHP and Zend
Extension Writing Part II: Parameters, Arrays, and ZVALs
Extension Writing Part II: Parameters, Arrays, and ZVALs [continued]
Extension Writing Part III: Resources
Warning: None of the code in this article is tested (sorry)

ENV['exec_start_time'] = microtime(true); .... echo "<!-- ", "After doing XYZ: ", (microtime(true) -  

Improve performace: check your loops

Before I start
I’ve always stayed away from writing a performance topic. There seems to be a lot of performance enthusiasts, benchmarking anything they can, in order to scoop off a few more percent of performance time. To my opinion, if your system is already reacting within an acceptable fashion, there is no need to try to further improve performance. Maintainability is a much more important topic to look at, at that point.

Finding out what is the problem
So you have a script which is not performing the way you want to. The first thing you should do it try to find out what the problem is. There are some tools out there that can help you. If you’re using Zend Studio, there is a profiler which shows you a tree of files and functions with the amount of processing time. (Warning: With Zend Studio 5, you need to close your project and all open files, otherwise you’ll get incorrect values). There is also a profiler in XDebug, which is a bit harder to set up, but works just as well (or even a bit better actually).

If you don’t have the option to install any of these tools, you can echo (or use FirePHP to output) the execution times, using the following script:

___FCKpd___0

Most likely the problem will be one of these three (in order of likeliness):

  1. A slow database query. Solving this is outside the scope of this article, but read this PDF about Query tuning for starters.
  2. To much is executed within a loop and/or the number of items for the loop is to big. Read the rest of the article.
  3. To much code is executed. This is probably cause of an abstraction layer that is simply to big or of to many abstraction layers. Try to do some refactoring, removing unnecessary abstraction or bypass abstraction on bottleneck positions.

Get the data ready before going into the loop
Looping through a large list in PHP can be very expensive performance wise, even if code in the loop is limited. If you’re looping through a mysql result, see if you can get the data as you want to use it from the query by using string, date and numeric functions and things like GROUP_CONCAT. Also try not to have to filter the data in PHP, you should only get the rows out the DB you actually need.

Don’t do things in the loop, you can also do outside it
Try to do as much stuff as possible outside of the loop. If an operation gives the same result for each item, you can surely put is outside of the loop.

Don’t do this:

___FCKpd___1

Instead do this:

___FCKpd___2

Use create_function to aid you
Sometimes you know you should put things outside of the loop, however the logic is so complex it can only be done in code. In that case you can use create_function together with array_map to help you out.

Don’t do this:

___FCKpd___3

Instead do this:

___FCKpd___4

Be careful with abstraction in loops
Things like iterators and overloading (__get/__set) are a lot slower than normal loops and getting and setting properties. When you have a lot of data it is probably better to stay a way of these kind of abstractions, especially if you only use them to make you code more pretty.
Also your own abstraction might be dangerous. The less code that is performed in a loop with lots of data, the better.

Sometimes you can prevent loops altogether
With PHP functions like join, array_sum and array_reduce and MySQL functions like GROUP_CONCAT, you may sometimes get out of using a PHP loop.

___FCKpd___5

Last resort: write an extension
If you have a piece of code in a loop which simply can not be written differently, but is causing mayor performance issues, see if you can rewrite that in C. Compiled code is simply a lot faster and will most likely solve your problem. The syntax of C is much like PHP, though there are a lot of gotcha’s. You can turn that C code into a PHP extension, so you can use it in your application. I’ve used the following articles to get started with PHP extensions:
Extension Writing Part I: Introduction to PHP and Zend
Extension Writing Part II: Parameters, Arrays, and ZVALs
Extension Writing Part II: Parameters, Arrays, and ZVALs [continued]
Extension Writing Part III: Resources
Warning: None of the code in this article is tested (sorry)

ENV
['exec_start_time']) * 1000, " ms", " -->/n" .... echo "<!-- ", "After doing SOMETHING: ", (microtime(true) -  

Improve performace: check your loops

Before I start
I’ve always stayed away from writing a performance topic. There seems to be a lot of performance enthusiasts, benchmarking anything they can, in order to scoop off a few more percent of performance time. To my opinion, if your system is already reacting within an acceptable fashion, there is no need to try to further improve performance. Maintainability is a much more important topic to look at, at that point.

Finding out what is the problem
So you have a script which is not performing the way you want to. The first thing you should do it try to find out what the problem is. There are some tools out there that can help you. If you’re using Zend Studio, there is a profiler which shows you a tree of files and functions with the amount of processing time. (Warning: With Zend Studio 5, you need to close your project and all open files, otherwise you’ll get incorrect values). There is also a profiler in XDebug, which is a bit harder to set up, but works just as well (or even a bit better actually).

If you don’t have the option to install any of these tools, you can echo (or use FirePHP to output) the execution times, using the following script:

___FCKpd___0

Most likely the problem will be one of these three (in order of likeliness):

  1. A slow database query. Solving this is outside the scope of this article, but read this PDF about Query tuning for starters.
  2. To much is executed within a loop and/or the number of items for the loop is to big. Read the rest of the article.
  3. To much code is executed. This is probably cause of an abstraction layer that is simply to big or of to many abstraction layers. Try to do some refactoring, removing unnecessary abstraction or bypass abstraction on bottleneck positions.

Get the data ready before going into the loop
Looping through a large list in PHP can be very expensive performance wise, even if code in the loop is limited. If you’re looping through a mysql result, see if you can get the data as you want to use it from the query by using string, date and numeric functions and things like GROUP_CONCAT. Also try not to have to filter the data in PHP, you should only get the rows out the DB you actually need.

Don’t do things in the loop, you can also do outside it
Try to do as much stuff as possible outside of the loop. If an operation gives the same result for each item, you can surely put is outside of the loop.

Don’t do this:

___FCKpd___1

Instead do this:

___FCKpd___2

Use create_function to aid you
Sometimes you know you should put things outside of the loop, however the logic is so complex it can only be done in code. In that case you can use create_function together with array_map to help you out.

Don’t do this:

___FCKpd___3

Instead do this:

___FCKpd___4

Be careful with abstraction in loops
Things like iterators and overloading (__get/__set) are a lot slower than normal loops and getting and setting properties. When you have a lot of data it is probably better to stay a way of these kind of abstractions, especially if you only use them to make you code more pretty.
Also your own abstraction might be dangerous. The less code that is performed in a loop with lots of data, the better.

Sometimes you can prevent loops altogether
With PHP functions like join, array_sum and array_reduce and MySQL functions like GROUP_CONCAT, you may sometimes get out of using a PHP loop.

___FCKpd___5

Last resort: write an extension
If you have a piece of code in a loop which simply can not be written differently, but is causing mayor performance issues, see if you can rewrite that in C. Compiled code is simply a lot faster and will most likely solve your problem. The syntax of C is much like PHP, though there are a lot of gotcha’s. You can turn that C code into a PHP extension, so you can use it in your application. I’ve used the following articles to get started with PHP extensions:
Extension Writing Part I: Introduction to PHP and Zend
Extension Writing Part II: Parameters, Arrays, and ZVALs
Extension Writing Part II: Parameters, Arrays, and ZVALs [continued]
Extension Writing Part III: Resources
Warning: None of the code in this article is tested (sorry)

ENV
['exec_start_time']) * 1000, " ms", " -->/n"

Most likely the problem will be one of these three (in order of likeliness):

  1. A slow database query. Solving this is outside the scope of this article, but read this PDF about Query tuning for starters.
  2. To much is executed within a loop and/or the number of items for the loop is to big. Read the rest of the article.
  3. To much code is executed. This is probably cause of an abstraction layer that is simply to big or of to many abstraction layers. Try to do some refactoring, removing unnecessary abstraction or bypass abstraction on bottleneck positions.

Get the data ready before going into the loop
Looping through a large list in PHP can be very expensive performance wise, even if code in the loop is limited. If you’re looping through a mysql result, see if you can get the data as you want to use it from the query by using string, date and numeric functions and things like GROUP_CONCAT. Also try not to have to filter the data in PHP, you should only get the rows out the DB you actually need.

Don’t do things in the loop, you can also do outside it
Try to do as much stuff as possible outside of the loop. If an operation gives the same result for each item, you can surely put is outside of the loop.

Don’t do this:

___FCKpd___1

Instead do this:

___FCKpd___2

Use create_function to aid you
Sometimes you know you should put things outside of the loop, however the logic is so complex it can only be done in code. In that case you can use create_function together with array_map to help you out.

Don’t do this:

___FCKpd___3

Instead do this:

___FCKpd___4

Be careful with abstraction in loops
Things like iterators and overloading (__get/__set) are a lot slower than normal loops and getting and setting properties. When you have a lot of data it is probably better to stay a way of these kind of abstractions, especially if you only use them to make you code more pretty.
Also your own abstraction might be dangerous. The less code that is performed in a loop with lots of data, the better.

Sometimes you can prevent loops altogether
With PHP functions like join, array_sum and array_reduce and MySQL functions like GROUP_CONCAT, you may sometimes get out of using a PHP loop.

___FCKpd___5

Last resort: write an extension
If you have a piece of code in a loop which simply can not be written differently, but is causing mayor performance issues, see if you can rewrite that in C. Compiled code is simply a lot faster and will most likely solve your problem. The syntax of C is much like PHP, though there are a lot of gotcha’s. You can turn that C code into a PHP extension, so you can use it in your application. I’ve used the following articles to get started with PHP extensions:
Extension Writing Part I: Introduction to PHP and Zend
Extension Writing Part II: Parameters, Arrays, and ZVALs
Extension Writing Part II: Parameters, Arrays, and ZVALs [continued]
Extension Writing Part III: Resources
Warning: None of the code in this article is tested (sorry)

**项目名称:** 基于Vue.js与Spring Cloud架构的博客系统设计与开发——微服务分布式应用实践 **项目概述:** 本项目为计算机科学与技术专业本科毕业设计成果,旨在设计并实现一个采用前后端分离架构的现代化博客平台。系统前端基于Vue.js框架构建,提供响应式用户界面;后端采用Spring Cloud微服务架构,通过服务拆分、注册发现、配置中心及网关路由等技术,构建高可用、易扩展的分布式应用体系。项目重点探讨微服务模式下的系统设计、服务治理、数据一致性及部署运维等关键问题,体现了分布式系统在Web应用中的实践价值。 **技术架构:** 1. **前端技术栈:** Vue.js 2.x、Vue Router、Vuex、Element UI、Axios 2. **后端技术栈:** Spring Boot 2.x、Spring Cloud (Eureka/Nacos、Feign/OpenFeign、Ribbon、Hystrix、Zuul/Gateway、Config) 3. **数据存储:** MySQL 8.0(主数据存储)、Redis(缓存与会话管理) 4. **服务通信:** RESTful API、消息队列(可选RabbitMQ/Kafka) 5. **部署与运维:** Docker容器化、Jenkins持续集成、Nginx负载均衡 **核心功能模块:** - 用户管理:注册登录、权限控制、个人中心 - 文章管理:富文本编辑、分类标签、发布审核、评论互动 - 内容展示:首页推荐、分类检索、全文搜索、热门排行 - 系统管理:后台仪表盘、用户与内容监控、日志审计 - 微服务治理:服务健康检测、动态配置更新、熔断降级策略 **设计特点:** 1. **架构解耦:** 前后端完全分离,通过API网关统一接入,支持独立开发与部署。 2. **服务拆分:** 按业务域划分为用户服务、文章服务、评论服务、文件服务等独立微服务。 3. **高可用设计:** 采用服务注册发现机制,配合负载均衡与熔断器,提升系统容错能力。 4. **可扩展性:** 模块化设计支持横向扩展,配置中心实现运行时动态调整。 **项目成果:** 完成了一个具备完整博客功能、具备微服务典型特征的分布式系统原型,通过容器化部署验证了多服务协同运行的可行性,为云原生应用开发提供了实践参考。 资源来源于网络分享,仅用于学习交流使用,请勿用于商业,如有侵权请联系我删除!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值