子魚@NET

渤海子魚的BLOG

阳东ID:ffyd2000
13490次访问,排名8409(-2)好友8人,关注者8
小二
ffyd2000的文章
原创 18 篇
翻译 0 篇
转载 21 篇
评论 3 篇
渤海子魚的公告
人生就像在风中扫落叶,只是顾着清扫眼前的落叶那是不会顺利的,如果顺着风向堆积落叶的话,那就会变得很轻松了.事物不能光用眼睛看,感觉也是很重要的,仅仅拘泥于眼前的事物,忽略其他的东西也是不行的.抛下邪念,接受现状,这才是所谓的领悟
最近评论
psnccs:WoW Gold
farmer_chs:转贴
SOW觉得文章哪里有问题呢?
SOW:没有搞过PHP不要把别人写的拿来乱说
文章分类
收藏
相册
MY PHOTOS
CD CSDNer
billy
Nosound
小新(RSS)
木头
牛蛙
白云
存档
软件项目交易
订阅我的博客
XML聚合  FeedSky
订阅到鲜果
订阅到Google
订阅到抓虾
订阅到BlogLines
订阅到Yahoo
订阅到GouGou
订阅到飞鸽
订阅到Rojo
订阅到newsgator
订阅到netvibes

转载 Improve performace: check your loops收藏

新一篇: MVC Web Project-eclipse下的struts2插件 | 旧一篇: ExtTLD -Simplifies ExtJS components for jee

 

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)

发表于 @ 2008年01月25日 14:04:00|评论(loading...)|编辑

新一篇: MVC Web Project-eclipse下的struts2插件 | 旧一篇: ExtTLD -Simplifies ExtJS components for jee

评论:没有评论。

发表评论  


登录
Csdn Blog version 3.1a
Copyright © 渤海子魚