<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>LetRails &#187; 性能</title>
	<atom:link href="http://www.letrails.cn/archives/category/%e6%80%a7%e8%83%bd/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.letrails.cn</link>
	<description></description>
	<lastBuildDate>Sat, 06 Aug 2011 07:02:18 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	
<atom:link rel="hub" href="http://pubsubhubbub.appspot.com"/><atom:link rel="hub" href="http://superfeedr.com/hubbub"/>		<item>
		<title>Rails性能优化简明指南</title>
		<link>http://www.letrails.cn/archives/rails-performance-optimization-guide/</link>
		<comments>http://www.letrails.cn/archives/rails-performance-optimization-guide/#comments</comments>
		<pubDate>Wed, 21 Jul 2010 12:35:14 +0000</pubDate>
		<dc:creator>Yuanyi ZHANG</dc:creator>
				<category><![CDATA[性能]]></category>

		<guid isPermaLink="false">http://www.letrails.cn/?p=215</guid>
		<description><![CDATA[最近多背一公斤的网站由于前段时间加了太多功能，但是没有考虑性能问题，导致速度下降，内存占用剧增，apache频频重启，需要进行优化，于是花了点时间学习了下rails的优化，整理成这篇文章，希望对遇到同样问题的人有用。 基本原则 大部分讲优化的文章都会在开头讲到优化的基本原则： 1. 不要过早优化，这里必须要提到Donald Knuth的名言：过早的优化是万恶之源，Premature optimization is the root of all evil，在你的应用还没有遇到性能问题之前，不要为性能担忧，也无需为优化浪费时间，只有当性能成为问题时才进行优化，这是第一原则。 2. 基准测试是必须的，没有基准测试，优化的效果就无从衡量，所有优化的第一步都应该是基准测试。 3. 要适可而止，不要追求极致。性能的优化实际上是个没有尽头的事情，没有任何一个应用可以在性能方面达到完美，只要你愿意，总是能找到可以优化的地方，但是这里要进行权衡，如果你的团队花了1个月的时间进行优化，而性能仅仅提高了10%，那么不如添置一台服务器，一台服务器的成本肯定要远远小于你的团队一个月的工资，另外，也没有必要为了一些可有可无的优化而牺牲代码的可读性，什么是可有可无的优化？比如直接写a标签肯定比link_to要快，调用 helper肯定也不如将所有代码写在view中快，但这样的优化得不偿失，没有意义。 看过了这些原则，如果你还认为你的应用需要优化，那就接着往下看吧！ request-log-analytizer 优化的第一个工作应该是找出问题所在，我要介绍的第一个工具request-log-analytizer，就是为这个工作准备的，这是一个日志分析工具，它可以通过对日志进行分析，找出应用的瓶颈所在，request-log-analytizer的好处就是所有的分析都是基于生产环境，避免了做无用功。 request-log-analytizer的使用非常简单： sudo gem install request-log-analytizer request-log-analytizer log/production.log 现在你就可以在命令行看到日志分析结果了，为了方便查看，request-log-analytizer也支持以HTML格式输出结果： request-log-analytizer -f log.html &#8211;output html log/production.log 用浏览器打开log.html，可以看到最上面是摘要，告诉你日志中总共有多少个请求，以及请求的时间跨度，下面一个部分是每个时间段的平均请求数，然后就是被请求次数最多的20个URL的请求信息，接下来是按照请求方法和响应分类的请求信息。 在这些信息的后面，就是我们关心的性能信息了，这里有6块，总处理时间最长的请求，平均处理时间最长的请求，总View渲染时间最长的请求，平均View渲染时间最长的请求，总数据库查询时间最长的请求以及平均数据库查询时间最长的请求，通过这6个部分，我们就可以了解到应用的性能瓶颈，在这6块后面，request-log-analytizer还列出了平均处理时间超过1秒的请求，这些应该是优化的重点，如下图，我们可以看出，1公斤的网站需要优化的请求是如此之多。 有了目标，下面就让我们来挨个处理它们。 Benchmark 在开始优化之前，还有一个工作就是基准测试，就像前面的优化准则提到的，只有做了基准测试，我们才能判断经过我们的优化，性能到底有没有提高，提高了多少？ Rails 从2.2开始内置了Benchmarker和Profiler工具，如果你新建一个Rails应用，在script/performance目录下就可以看到它们，你也可以通过performance_test这个generator来生成新的性能测试用例，关于Rails的性能测试，请参考Rails的官方指南（http://guides.rubyonrails.org/performance_testing.html），介绍非常详细，但是这里我们要解决的是生产环境的问题，测试环境很难模拟出生产环境中的数据，所以这里我们需要用到rails的benchmarker脚本： $ RAILS_ENV=production ruby script/performance/benchmarker 4 "ActionController::Integration::Session.new.get_via_redirect('/activities')" user system total real #1 2.720000 0.040000 [...]<table class="wumii-related-items" cellspacing="0" cellpadding="2" border="0" width="100%" style="clear: both;">
    
    <tr>
        <td ><b><font size="-1"  style="display: block !important; padding: 20px 0 5px !important;">无觅猜您也喜欢：</font></b></td>
    </tr>
    
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fupgrade-to-rails-3-beta%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Frails-performance-optimization-guide%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">升级到Rails 3 Beta</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fusing-rails-reviewer-analytize-rails-performance%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Frails-performance-optimization-guide%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">使用rails_reviewer优化Rails数据库查询性能</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Frails-2-2-i18n-tutorials%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Frails-performance-optimization-guide%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">Rails 2.2 国际化(i18n) 简明指南</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fxapian-vs-sphinx-in-rails%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Frails-performance-optimization-guide%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">Xapian，Sphinx在Rails中的性能比较</font>
                    </a>
                </td>
            </tr>
    
    <tr>
        <td  align="right">
            <a style="text-decoration: none !important;" href="http://www.wumii.com/widget/relatedItems.htm" target="_blank" title="无觅相关文章插件">
                <font size="-1" color="#bbbbbb" style="display: block !important; font-family: arial !important; padding: 5px 0 !important; font-size: 12px !important; color: #bbb !important;">无觅</font>
            </a>
        </td>
    </tr>
</table>]]></description>
			<content:encoded><![CDATA[<p>最近<a href="http://www.1kg.org">多背一公斤</a>的网站由于前段时间加了太多功能，但是没有考虑性能问题，导致速度下降，内存占用剧增，apache频频重启，需要进行优化，于是花了点时间学习了下rails的优化，整理成这篇文章，希望对遇到同样问题的人有用。</p>
<p><span id="more-215"></span>基本原则</p>
<p>大部分讲优化的文章都会在开头讲到优化的基本原则：</p>
<p>1. 不要过早优化，这里必须要提到<a href="http://en.wikiquote.org/wiki/Donald_Knuth">Donald Knuth</a>的名言：过早的优化是万恶之源，Premature optimization is the root of all evil，在你的应用还没有遇到性能问题之前，不要为性能担忧，也无需为优化浪费时间，只有当性能成为问题时才进行优化，这是第一原则。</p>
<p>2. 基准测试是必须的，没有基准测试，优化的效果就无从衡量，所有优化的第一步都应该是基准测试。</p>
<p>3. 要适可而止，不要追求极致。性能的优化实际上是个没有尽头的事情，没有任何一个应用可以在性能方面达到完美，只要你愿意，总是能找到可以优化的地方，但是这里要进行权衡，如果你的团队花了1个月的时间进行优化，而性能仅仅提高了10%，那么不如添置一台服务器，一台服务器的成本肯定要远远小于你的团队一个月的工资，另外，也没有必要为了一些可有可无的优化而牺牲代码的可读性，什么是可有可无的优化？比如直接写a标签肯定比link_to要快，调用 helper肯定也不如将所有代码写在view中快，但这样的优化得不偿失，没有意义。</p>
<p>看过了这些原则，如果你还认为你的应用需要优化，那就接着往下看吧！</p>
<p>request-log-analytizer</p>
<p>优化的第一个工作应该是找出问题所在，我要介绍的第一个工具<a href="http://github.com/wvanbergen/request-log-analyzer">request-log-analytizer</a>，就是为这个工作准备的，这是一个日志分析工具，它可以通过对日志进行分析，找出应用的瓶颈所在，request-log-analytizer的好处就是所有的分析都是基于生产环境，避免了做无用功。</p>
<p>request-log-analytizer的使用非常简单：</p>
<p class="code"><code class="ruby"><br />
sudo gem install request-log-analytizer<br />
request-log-analytizer log/production.log<br />
</code></p>
<p>现在你就可以在命令行看到日志分析结果了，为了方便查看，request-log-analytizer也支持以HTML格式输出结果：</p>
<p>request-log-analytizer -f log.html &#8211;output html log/production.log</p>
<p>用浏览器打开log.html，可以看到最上面是摘要，告诉你日志中总共有多少个请求，以及请求的时间跨度，下面一个部分是每个时间段的平均请求数，然后就是被请求次数最多的20个URL的请求信息，接下来是按照请求方法和响应分类的请求信息。</p>
<p>在这些信息的后面，就是我们关心的性能信息了，这里有6块，总处理时间最长的请求，平均处理时间最长的请求，总View渲染时间最长的请求，平均View渲染时间最长的请求，总数据库查询时间最长的请求以及平均数据库查询时间最长的请求，通过这6个部分，我们就可以了解到应用的性能瓶颈，在这6块后面，request-log-analytizer还列出了平均处理时间超过1秒的请求，这些应该是优化的重点，如下图，我们可以看出，1公斤的网站需要优化的请求是如此之多。</p>
<p><a href="http://www.letrails.cn/wp-content/uploads/2010/07/Screen-shot-2010-07-21-at-6.51.30-PM.png"><img class="alignnone size-medium wp-image-224" title="Screen shot 2010-07-21 at 6.51.30 PM" src="http://www.letrails.cn/wp-content/uploads/2010/07/Screen-shot-2010-07-21-at-6.51.30-PM-300x206.png" alt="" width="300" height="206" /></a></p>
<p>有了目标，下面就让我们来挨个处理它们。</p>
<p>Benchmark</p>
<p>在开始优化之前，还有一个工作就是基准测试，就像前面的优化准则提到的，只有做了基准测试，我们才能判断经过我们的优化，性能到底有没有提高，提高了多少？</p>
<p>Rails 从2.2开始内置了Benchmarker和Profiler工具，如果你新建一个Rails应用，在script/performance目录下就可以看到它们，你也可以通过performance_test这个generator来生成新的性能测试用例，关于Rails的性能测试，请参考Rails的官方指南（http://guides.rubyonrails.org/performance_testing.html），介绍非常详细，但是这里我们要解决的是生产环境的问题，测试环境很难模拟出生产环境中的数据，所以这里我们需要用到rails的benchmarker脚本：</p>
<p class="code"><code class="ruby"><br />
$ RAILS_ENV=production ruby script/performance/benchmarker 4 "ActionController::Integration::Session.new.get_via_redirect('/activities')"<br />
user     system      total        real<br />
#1      2.720000   0.040000   2.760000 (  4.861908)<br />
</code></p>
<p>这条命令需要说明一下，首先我们设置benchmarker运行在production环境，第一个参数4是告诉benchmarker脚本的运行次数，第二个参数就是我们的测试，ActionController::Integration::Session是Rails提供的集成测试框架，可以用来模拟用户请求，这里我们看到，未优化前，处理4个/activities请求花去了2.76秒的时间，现在我们就有了一个判断的标准，后面我们就可以通过这条命令来检验我们的优化提高了多少性能。</p>
<p>不过不幸的是，Rails自从2.3.4版本开始，引入了一个Bug，导致这条命令不能在Mac系统运行，如果你使用的是mac系统，可以将Rails降回2.3.4以下版本，或者直接在console运行：</p>
<p class="code"><code class="ruby"><br />
Benchmark.bm do |x|<br />
x.report { 4.times { app.get(“/activities”) }}<br />
end<br />
</code></p>
<p>除了benchmarker，rails还内置了一个profiler脚本，是对ruby-prof的封装，你也可以用这个工具对你的action进行profiler测试，看看到底是那个函数调用浪费了时间：</p>
<p class="code"><code class="ruby"><br />
$ RAILS_ENV=production ruby script/performance/profiler "ActionController::Integration::Session.new.get_via_redirect('/activities')"<br />
</code></p>
<p>query_reviewer</p>
<p>有了优化基准，下面就让我们以/activities为例，来看看应该如何进行优化，通过request-log-analytizer我们看到，这个请求的花销主要在数据库上，所以优化的关键就是减少和优化数据库查询，<a href="http://github.com/dsboulder/query_reviewer">query_reviewer</a>就是为这个工作准备的，它实际上是mysql的 explain命令的封装，query_reviewer的安装非常简单，安装完成后，会在页面的左上角出现一个小的方框，点击就会显示当前页面的SQL 查询需要进行哪些优化，下面是1公斤的/activities页面的输出：</p>
<p><a href="http://www.letrails.cn/wp-content/uploads/2010/07/Screen-shot-2010-07-21-at-7.19.38-PM.png"><img class="alignnone size-medium wp-image-225" title="Screen shot 2010-07-21 at 7.19.38 PM" src="http://www.letrails.cn/wp-content/uploads/2010/07/Screen-shot-2010-07-21-at-7.19.38-PM-300x188.png" alt="" width="300" height="188" /></a></p>
<p>从上图可以看出，这个请求进行了65次数据库查询，并且存在18个错误，经过对这些查询进行优化以及增加counter cache后，成功的将查询减到了8条，时间也从0.534减到了0.012，速度提高了44倍：</p>
<p><a href="http://www.letrails.cn/wp-content/uploads/2010/07/Screen-shot-2010-07-21-at-8.01.04-PM.png"><img class="alignnone size-medium wp-image-226" title="Screen shot 2010-07-21 at 8.01.04 PM" src="http://www.letrails.cn/wp-content/uploads/2010/07/Screen-shot-2010-07-21-at-8.01.04-PM-300x202.png" alt="" width="300" height="202" /></a></p>
<p>bullet</p>
<p>这里还要顺便介绍一下国人<a href="http://github.com/flyerhzm/bullet">flyerhzm开发的bullet插件</a>，这是一个用于检测eager loading的插件，可以有效减少SQL查询的数量，安装成功后，它会在有问题的页面给出下图这样的提示：</p>
<p><a href="http://www.letrails.cn/wp-content/uploads/2010/07/Screen-shot-2010-07-21-at-7.56.32-PM.png"><img class="alignnone size-medium wp-image-227" title="Screen shot 2010-07-21 at 7.56.32 PM" src="http://www.letrails.cn/wp-content/uploads/2010/07/Screen-shot-2010-07-21-at-7.56.32-PM-300x104.png" alt="" width="300" height="104" /></a></p>
<p>上图告诉你应该在调用Photo的find方法时包含:activity对象，这样就不用为每个photo对象再单独查询一次activity了。</p>
<p>好了，经过上面的优化，让我们再来运行benchmarker检验一下效果吧：</p>
<p class="code"><code class="ruby"><br />
$ RAILS_ENV=production ruby script/performance/benchmarker 4 "ActionController::Integration::Session.new.get_via_redirect('/activities')"<br />
user     system      total        real<br />
#1      0.680000   0.000000   0.680000 (  0.696291)<br />
</code></p>
<p>可以看到，经过这番优化，对/activities页面的请求从2.76秒降到了0.68秒，提高了超过2秒，单个请求提高了0.5秒，任务完成。</p>
<p>不过如果你的问题在于view渲染过慢，或者经过上面的优化，数据库的性能依然不能令人满意，那你可能就需要增加页面缓存，或者是借助大名鼎鼎的memcached了，关于这两个的介绍可以参看下面的文章：</p>
<p>Rails缓存：<a href="http://railsenvy.com/2007/2/28/rails-caching-tutorial">http://railsenvy.com/2007/2/28/rails-caching-tutorial</a><br />
Rails Memcached：<a href="http://nubyonrails.com/articles/memcached-basics-for-rails">http://nubyonrails.com/articles/memcached-basics-for-rails</a></p>
<table class="wumii-related-items" cellspacing="0" cellpadding="2" border="0" width="100%" style="clear: both;">
    
    <tr>
        <td ><b><font size="-1"  style="display: block !important; padding: 20px 0 5px !important;">无觅猜您也喜欢：</font></b></td>
    </tr>
    
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fupgrade-to-rails-3-beta%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Frails-performance-optimization-guide%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">升级到Rails 3 Beta</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fusing-rails-reviewer-analytize-rails-performance%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Frails-performance-optimization-guide%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">使用rails_reviewer优化Rails数据库查询性能</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Frails-2-2-i18n-tutorials%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Frails-performance-optimization-guide%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">Rails 2.2 国际化(i18n) 简明指南</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fxapian-vs-sphinx-in-rails%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Frails-performance-optimization-guide%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">Xapian，Sphinx在Rails中的性能比较</font>
                    </a>
                </td>
            </tr>
    
    <tr>
        <td  align="right">
            <a style="text-decoration: none !important;" href="http://www.wumii.com/widget/relatedItems.htm" target="_blank" title="无觅相关文章插件">
                <font size="-1" color="#bbbbbb" style="display: block !important; font-family: arial !important; padding: 5px 0 !important; font-size: 12px !important; color: #bbb !important;">无觅</font>
            </a>
        </td>
    </tr>
</table>]]></content:encoded>
			<wfw:commentRss>http://www.letrails.cn/archives/rails-performance-optimization-guide/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>使用rails_reviewer优化Rails数据库查询性能</title>
		<link>http://www.letrails.cn/archives/using-rails-reviewer-analytize-rails-performance/</link>
		<comments>http://www.letrails.cn/archives/using-rails-reviewer-analytize-rails-performance/#comments</comments>
		<pubDate>Mon, 23 Mar 2009 10:25:18 +0000</pubDate>
		<dc:creator>yuanyi</dc:creator>
				<category><![CDATA[性能]]></category>

		<guid isPermaLink="false">http://www.letrails.cn/archives/using-rails-reviewer-analytize-rails-performance</guid>
		<description><![CDATA[最近在做的一个项目遇到严重的性能问题，主要是数据库查询过多，同事向我推荐了rails_reviewer插件，它是我的前同事（不确定我进公司时他还在不在） David Stevenson 写的一个帮助你优化SQL查询的插件，它可以帮助你定位数据库查询的瓶颈所在，从而通过编制索引已经缓存关键变量来改进性能。 rails_reviewer的安装很简单： $ script/plugin install git://github.com/dsboulder/query_reviewer.git $ rake query_reviewer:setup 现在重启服务器，你就会在屏幕的左上角看到一个小窗口，点击这个窗口，就会显示加载当前页面的所有SQL查询，并且会告诉你那些是没问题的，那些是需要优化的，如下图： 可以看到，在优化前这个请求执行了1101条SQL查询，并且大部分都是没有cache的，你可以通过rails_reviewer查看每条查询的SQL语 句以及代码的调用栈，优化主要从两方面进行，一个是提高查询性能，这个可以通过添加索引，另一个就是减少查询数量，这个可以通过缓存变量，比如： def production(name) &#160;&#160;@production_cache &#124;&#124;= {} &#160;&#160;@production_cache[name] &#124;&#124;= buildings.map{&#124;b&#124; b.production(name)}.sum end 下面是优化后的结果，可以看到，优化后查询数从1101变成了94，时间则从800多毫秒减到了59毫秒，大约只有原来的10分之一不到：<table class="wumii-related-items" cellspacing="0" cellpadding="3" border="0"  style="clear: both;">
    
    <tr>
        <td colspan="4"><b><font size="-1"  style="display: block !important; padding: 20px 0 5px !important;">无觅猜您也喜欢：</font></b></td>
    </tr>
    
        <tr>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important;">
                    <a target="_blank" title="Rails性能优化简明指南" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Frails-performance-optimization-guide%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fusing-rails-reviewer-analytize-rails-performance%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/site_images/2011/03/08/3251308.png" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">Rails性能优化简明指南</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="升级到Rails 3 Beta" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fupgrade-to-rails-3-beta%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fusing-rails-reviewer-analytize-rails-performance%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/images/blogWidget/wordpress_default.gif" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">升级到Rails 3 Beta</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="Rails Templates" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Frails-templates%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fusing-rails-reviewer-analytize-rails-performance%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/images/blogWidget/wordpress_default.gif" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">Rails Templates</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="Rails2.0新特性介绍（ 下）" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2F07-11-23-rails20-features%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fusing-rails-reviewer-analytize-rails-performance%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/site_images/2011/03/08/3251634.png" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">Rails2.0新特性介绍（ 下）</font>
                    </a>
                </td>
        </tr>
    
    <tr>
        <td colspan="4" align="right">
            <a style="text-decoration: none !important;" href="http://www.wumii.com/widget/relatedItems.htm" target="_blank" title="无觅相关文章插件">
                <font size="-1" color="#bbbbbb" style="display: block !important; font-family: arial !important; padding: 5px 0 !important; font-size: 12px !important; color: #bbb !important;">无觅</font>
            </a>
        </td>
    </tr>
</table>]]></description>
			<content:encoded><![CDATA[<p>最近在做的一个项目遇到严重的性能问题，主要是数据库查询过多，同事向我推荐了<a href="http://code.google.com/p/query-reviewer/">rails_reviewer</a>插件，它是我的前同事（不确定我进公司时他还在不在） <a href="http://flouri.sh/">David Stevenson</a> 写的一个帮助你优化SQL查询的插件，它可以帮助你定位数据库查询的瓶颈所在，从而通过编制索引已经缓存关键变量来改进性能。</p>
<p>rails_reviewer的安装很简单：</p>
<p class="code"><code class="ruby">$ script/plugin install git://github.com/dsboulder/query_reviewer.git<br />
$ rake query_reviewer:setup</code></p>
<p>现在重启服务器，你就会在屏幕的左上角看到一个小窗口，点击这个窗口，就会显示加载当前页面的所有SQL查询，并且会告诉你那些是没问题的，那些是需要优化的，如下图：</p>
<p><a href='http://lilac.greatweb.cn/rails/wp-content/uploads/2009/03/picture-1.png' title='picture-1.png'><img src='http://lilac.greatweb.cn/rails/wp-content/uploads/2009/03/picture-1.png' alt='picture-1.png' width="380" /></a></p>
<p>可以看到，在优化前这个请求执行了1101条SQL查询，并且大部分都是没有cache的，你可以通过rails_reviewer查看每条查询的SQL语 句以及代码的调用栈，优化主要从两方面进行，一个是提高查询性能，这个可以通过添加索引，另一个就是减少查询数量，这个可以通过缓存变量，比如：</p>
<p class="code"><code class="ruby"><br />
def production(name)<br />
&nbsp;&nbsp;@production_cache ||= {}<br />
&nbsp;&nbsp;@production_cache[name] ||= buildings.map{|b| b.production(name)}.sum<br />
end</code></p>
<p>下面是优化后的结果，可以看到，优化后查询数从1101变成了94，时间则从800多毫秒减到了59毫秒，大约只有原来的10分之一不到：</p>
<p><img src='http://lilac.greatweb.cn/rails/wp-content/uploads/2009/03/picture-2.png' alt='picture-2.png' width="400" /></p>
<table class="wumii-related-items" cellspacing="0" cellpadding="3" border="0"  style="clear: both;">
    
    <tr>
        <td colspan="4"><b><font size="-1"  style="display: block !important; padding: 20px 0 5px !important;">无觅猜您也喜欢：</font></b></td>
    </tr>
    
        <tr>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important;">
                    <a target="_blank" title="Rails性能优化简明指南" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Frails-performance-optimization-guide%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fusing-rails-reviewer-analytize-rails-performance%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/site_images/2011/03/08/3251308.png" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">Rails性能优化简明指南</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="升级到Rails 3 Beta" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fupgrade-to-rails-3-beta%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fusing-rails-reviewer-analytize-rails-performance%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/images/blogWidget/wordpress_default.gif" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">升级到Rails 3 Beta</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="Rails Templates" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Frails-templates%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fusing-rails-reviewer-analytize-rails-performance%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/images/blogWidget/wordpress_default.gif" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">Rails Templates</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="Rails2.0新特性介绍（ 下）" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2F07-11-23-rails20-features%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fusing-rails-reviewer-analytize-rails-performance%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/site_images/2011/03/08/3251634.png" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">Rails2.0新特性介绍（ 下）</font>
                    </a>
                </td>
        </tr>
    
    <tr>
        <td colspan="4" align="right">
            <a style="text-decoration: none !important;" href="http://www.wumii.com/widget/relatedItems.htm" target="_blank" title="无觅相关文章插件">
                <font size="-1" color="#bbbbbb" style="display: block !important; font-family: arial !important; padding: 5px 0 !important; font-size: 12px !important; color: #bbb !important;">无觅</font>
            </a>
        </td>
    </tr>
</table>]]></content:encoded>
			<wfw:commentRss>http://www.letrails.cn/archives/using-rails-reviewer-analytize-rails-performance/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Xapian，Sphinx在Rails中的性能比较</title>
		<link>http://www.letrails.cn/archives/xapian-vs-sphinx-in-rails/</link>
		<comments>http://www.letrails.cn/archives/xapian-vs-sphinx-in-rails/#comments</comments>
		<pubDate>Tue, 06 Jan 2009 09:22:25 +0000</pubDate>
		<dc:creator>yuanyi</dc:creator>
				<category><![CDATA[性能]]></category>

		<guid isPermaLink="false">http://www.letrails.cn/archives/xapian-vs-sphinx-in-rails</guid>
		<description><![CDATA[Xapian 和 Sphinx都是非常棒的开源全文搜索解决方案，但是我想知道哪个性能更好一些，Xapian官方提供了与Solr的对比，但是没有和Sphinx的，所以我决定自己来测试。 这两个都是开源的解决方案，你可以使用他们来搜索任何关键字比如马，桃子或者是Getminted等等，也可以使用通配符进行更广范围的查询。 数据集 要测试首先需要准备好数据集，我的数据是大约12000条blog记录，每个记录有两个字段需要搜索：title, description，代码如下： class Blog < ActiveRecord::Base &#160;&#160;# Thinking sphinx indexes &#160;&#160;define_index do &#160;&#160;&#160;&#160;indexes :title &#160;&#160;&#160;&#160;indexes :description &#160;&#160;end &#160;&#160;# Acts_as_xapian indexes &#160;&#160;acts_as_xapian :texts => [ :title, :description ] &#160;&#160; ... end 测试环境 下面是我的测试环境： Sphinx: 0.9.8 Xapian: 1.0.1 Sphinx plugin: thinking_sphinx Xapian plugin: acts_as_xapian Ruby: 1.8.6 p114 Rails: 2.1.0 Mysql: 5.0.51 OS: [...]<table class="wumii-related-items" cellspacing="0" cellpadding="2" border="0" width="100%" style="clear: both;">
    
    <tr>
        <td ><b><font size="-1"  style="display: block !important; padding: 20px 0 5px !important;">无觅猜您也喜欢：</font></b></td>
    </tr>
    
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fupgrade-to-rails-3-beta%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fxapian-vs-sphinx-in-rails%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">升级到Rails 3 Beta</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Frails-performance-optimization-guide%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fxapian-vs-sphinx-in-rails%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">Rails性能优化简明指南</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fusing-rails-reviewer-analytize-rails-performance%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fxapian-vs-sphinx-in-rails%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">使用rails_reviewer优化Rails数据库查询性能</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Frails-chart-solutions%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fxapian-vs-sphinx-in-rails%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">Rails 图表解决方案汇总</font>
                    </a>
                </td>
            </tr>
    
    <tr>
        <td  align="right">
            <a style="text-decoration: none !important;" href="http://www.wumii.com/widget/relatedItems.htm" target="_blank" title="无觅相关文章插件">
                <font size="-1" color="#bbbbbb" style="display: block !important; font-family: arial !important; padding: 5px 0 !important; font-size: 12px !important; color: #bbb !important;">无觅</font>
            </a>
        </td>
    </tr>
</table>]]></description>
			<content:encoded><![CDATA[<p><a href="http://xapian.org/">Xapian</a> 和 <a href="http://www.sphinxsearch.com/">Sphinx</a>都是非常棒的开源全文搜索解决方案，但是我想知道哪个性能更好一些，Xapian官方提供了与Solr的对比，但是没有和Sphinx的，所以我决定自己来测试。</p>
<p>这两个都是开源的解决方案，你可以使用他们来搜索任何关键字比如马，桃子或者是<u><a href="http://www.getminted.com/">Getminted</a></u>等等，也可以使用通配符进行更广范围的查询。</p>
<h2>数据集</h2>
<p>要测试首先需要准备好数据集，我的数据是大约12000条blog记录，每个记录有两个字段需要搜索：title, description，代码如下：</p>
<p class="code"><code class="ruby"><br />
class Blog < ActiveRecord::Base<br />
&nbsp;&nbsp;# Thinking sphinx indexes<br />
&nbsp;&nbsp;define_index do<br />
&nbsp;&nbsp;&nbsp;&nbsp;indexes :title<br />
&nbsp;&nbsp;&nbsp;&nbsp;indexes :description<br />
&nbsp;&nbsp;end<br />
&nbsp;&nbsp;# Acts_as_xapian indexes<br />
&nbsp;&nbsp;acts_as_xapian :texts => [ :title, :description ]<br />
&nbsp;&nbsp; ...<br />
end</code></p>
<h2>测试环境</h2>
<p>下面是我的测试环境：</p>
<ul>
<li>Sphinx: 0.9.8</li>
<li>Xapian: 1.0.1</li>
<li>Sphinx plugin: <a href="http://ts.freelancing-gods.com/">thinking_sphinx</a></li>
<li>Xapian plugin: <a href="http://github.com/frabcus/acts_as_xapian/tree/master">acts_as_xapian</a></li>
<li>Ruby: 1.8.6 p114</li>
<li>Rails: 2.1.0</li>
<li>Mysql: 5.0.51</li>
<li>OS: OS X 10.5.6</li>
<li>CPU: Intel Core 2 Duo 2.0G</li>
<li>Ram: 4G</li>
</ul>
<h2>索引</h2>
<p>我们首先来看看索引的性能：</p>
<p class="code"><code class="ruby"><br />
$ time rake xapian:rebuild_index models="Blog"<br />
real    2m12.942s<br />
user    0m24.569s<br />
sys    0m12.798s<br />
$ time rake thinking_sphinx:index<br />
real    1m53.543s<br />
user    0m4.725s<br />
sys    0m0.887s</code></p>
<p>结果显示Sphinx稍微快一点，但是因为Sphinx有索引进度提示，所以感觉上Sphinx快了好多。</p>
<h2>查询</h2>
<p>下面来看查询性能</p>
<p class="code"><code class="ruby"><br />
keywords = ['key1', 'key2', ..., 'key30']<br />
Benchmark.bm do |x|<br />
&nbsp;&nbsp;x.report("Xapian") { 30.times {|i| ActsAsXapian::Search.new "Blog", keywords[i], :limit => 10 } }<br />
&nbsp;&nbsp;x.report("Sphinx") { 30.times {|i| Blog.search keywords[i], :per_page => 10, :page => 1 }}<br />
end</code></p>
<p>这里我首先定义了30个关键字，每个关键字的匹配结果都在10个以上，然后用它们分别进行查询，因为可能有缓存的关系，所以每个查询只执行了一次，下面是结果：</p>
<p class="code"><code class="ruby"><br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;user&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;system&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;total&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;real<br />
Xapian&nbsp;&nbsp;0.020000&nbsp;&nbsp;&nbsp;0.020000&nbsp;&nbsp;&nbsp;0.040000&nbsp;(&nbsp;&nbsp;0.042381)<br />
Sphinx&nbsp;&nbsp;0.150000&nbsp;&nbsp;&nbsp;0.030000&nbsp;&nbsp;&nbsp;0.180000&nbsp;(&nbsp;&nbsp;0.285173)<br />
</code></p>
<p>结果显示，Xapian要快很多，但因为我的数据集实在是太小，所以可能并不能说明问题，这个结果仅供参考，当然，我想大部分人恐怕还是会选择Sphinx，因为Xapian的Rails插件acts_as_xapian实在是太难用了。</p>
<table class="wumii-related-items" cellspacing="0" cellpadding="2" border="0" width="100%" style="clear: both;">
    
    <tr>
        <td ><b><font size="-1"  style="display: block !important; padding: 20px 0 5px !important;">无觅猜您也喜欢：</font></b></td>
    </tr>
    
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fupgrade-to-rails-3-beta%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fxapian-vs-sphinx-in-rails%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">升级到Rails 3 Beta</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Frails-performance-optimization-guide%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fxapian-vs-sphinx-in-rails%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">Rails性能优化简明指南</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fusing-rails-reviewer-analytize-rails-performance%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fxapian-vs-sphinx-in-rails%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">使用rails_reviewer优化Rails数据库查询性能</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Frails-chart-solutions%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fxapian-vs-sphinx-in-rails%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">Rails 图表解决方案汇总</font>
                    </a>
                </td>
            </tr>
    
    <tr>
        <td  align="right">
            <a style="text-decoration: none !important;" href="http://www.wumii.com/widget/relatedItems.htm" target="_blank" title="无觅相关文章插件">
                <font size="-1" color="#bbbbbb" style="display: block !important; font-family: arial !important; padding: 5px 0 !important; font-size: 12px !important; color: #bbb !important;">无觅</font>
            </a>
        </td>
    </tr>
</table>]]></content:encoded>
			<wfw:commentRss>http://www.letrails.cn/archives/xapian-vs-sphinx-in-rails/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>使用YSlow提升应用性能</title>
		<link>http://www.letrails.cn/archives/yslow-intro/</link>
		<comments>http://www.letrails.cn/archives/yslow-intro/#comments</comments>
		<pubDate>Sun, 04 May 2008 13:51:31 +0000</pubDate>
		<dc:creator>yuanyi</dc:creator>
				<category><![CDATA[性能]]></category>

		<guid isPermaLink="false">http://www.letrails.cn/archives/yslow-intro</guid>
		<description><![CDATA[YSlow出来有一阵了，今天用了下，感觉还不错，即使你对性能优化是个外行，通过YSlow，你也可以让你的应用性能轻松得到提升。 YSlow通过分析你的应用是否符合“网页加速最佳实践”中的规则来给你的应用打分，判断的标准包括：HTTP请求数应该尽可能少，尽量减少DNS查询，尽量使用GZip压缩，CSS放在顶部，JS放在底部，使用GET发送AJAX请求，完整列表参看”最佳实践“。 这是我目前在做项目的YSlow测试结果，YSlow采用A-F评分制，A最好，F最差，可以看到，这个项目的性能隐患相当严重。 要使用YSlow，你需要首先安装Firebug，目前只支持Firefox。<table class="wumii-related-items" cellspacing="0" cellpadding="2" border="0" width="100%" style="clear: both;">
    
    <tr>
        <td ><b><font size="-1"  style="display: block !important; padding: 20px 0 5px !important;">无觅猜您也喜欢：</font></b></td>
    </tr>
    
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2F13%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fyslow-intro%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">Rails应用性能优化2</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2F12%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fyslow-intro%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">Rails应用性能优化1</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2F16%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fyslow-intro%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">Rails应用性能优化3</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2F17%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fyslow-intro%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">Rails应用性能优化4</font>
                    </a>
                </td>
            </tr>
    
    <tr>
        <td  align="right">
            <a style="text-decoration: none !important;" href="http://www.wumii.com/widget/relatedItems.htm" target="_blank" title="无觅相关文章插件">
                <font size="-1" color="#bbbbbb" style="display: block !important; font-family: arial !important; padding: 5px 0 !important; font-size: 12px !important; color: #bbb !important;">无觅</font>
            </a>
        </td>
    </tr>
</table>]]></description>
			<content:encoded><![CDATA[<p><a href="http://developer.yahoo.com/yslow/">YSlow</a>出来有一阵了，今天用了下，感觉还不错，即使你对性能优化是个外行，通过YSlow，你也可以让你的应用性能轻松得到提升。</p>
<p>YSlow通过分析你的应用是否符合“<a href="http://developer.yahoo.com/performance/index.html#rules">网页加速最佳实践</a>”中的规则来给你的应用打分，判断的标准包括：HTTP请求数应该尽可能少，尽量减少DNS查询，尽量使用GZip压缩，CSS放在顶部，JS放在底部，使用GET发送AJAX请求，完整列表参看”最佳实践“。</p>
<p><a href='http://lilac.greatweb.cn/rails/wp-content/uploads/2008/05/picture-1.png' title='picture-1.png'><img src='http://lilac.greatweb.cn/rails/wp-content/uploads/2008/05/picture-1.png' alt='picture-1.png'  width="380" /></a></p>
<p>这是我目前在做项目的YSlow测试结果，YSlow采用A-F评分制，A最好，F最差，可以看到，这个项目的性能隐患相当严重。</p>
<p>要使用YSlow，你需要首先安装<a href="http://www.getfirebug.com/">Firebug</a>，目前只支持Firefox。</p>
<table class="wumii-related-items" cellspacing="0" cellpadding="2" border="0" width="100%" style="clear: both;">
    
    <tr>
        <td ><b><font size="-1"  style="display: block !important; padding: 20px 0 5px !important;">无觅猜您也喜欢：</font></b></td>
    </tr>
    
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2F13%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fyslow-intro%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">Rails应用性能优化2</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2F12%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fyslow-intro%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">Rails应用性能优化1</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2F16%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fyslow-intro%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">Rails应用性能优化3</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2F17%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fyslow-intro%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">Rails应用性能优化4</font>
                    </a>
                </td>
            </tr>
    
    <tr>
        <td  align="right">
            <a style="text-decoration: none !important;" href="http://www.wumii.com/widget/relatedItems.htm" target="_blank" title="无觅相关文章插件">
                <font size="-1" color="#bbbbbb" style="display: block !important; font-family: arial !important; padding: 5px 0 !important; font-size: 12px !important; color: #bbb !important;">无觅</font>
            </a>
        </td>
    </tr>
</table>]]></content:encoded>
			<wfw:commentRss>http://www.letrails.cn/archives/yslow-intro/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>使用SQLite in memory提高测试代码效率</title>
		<link>http://www.letrails.cn/archives/55/</link>
		<comments>http://www.letrails.cn/archives/55/#comments</comments>
		<pubDate>Thu, 23 Aug 2007 16:21:01 +0000</pubDate>
		<dc:creator>Yuanyi ZHANG</dc:creator>
				<category><![CDATA[性能]]></category>
		<category><![CDATA[数据库]]></category>
		<category><![CDATA[测试]]></category>

		<guid isPermaLink="false">http://www.letrails.cn/archives/55</guid>
		<description><![CDATA[对于需要进行持续集成的大型项目来说，运行测试代码的花费就显得尤为重要，Chris Roos在这篇帖子里介绍了一种通过使用SQLite数据库来 提高测试代码运行效率的方法。 首先你需要安装SQLite3以及sqlite3-ruby gem，然后修改database.yml： test: adapter: sqlite3 database: ":memory:" 但是这样有一个问题，由于SQLite数据库保存在内存中，因此必须在每次执行单元测试之前首先生成数据库的大纲，不过不用担心，Chris Roos已经提供了一段现成的代码，将它加到你的environment.rb就可以了： def in_memory_database? &#160;&#160;ENV["RAILS_ENV"] == "test" and &#160;&#160;ActiveRecord::Base.connection.class == ActiveRecord::ConnectionAdapters::SQLite3Adapter and &#160;&#160;Rails::Configuration.new.database_configuration['test']['database'] == ':memory:' end if in_memory_database? &#160;&#160;puts "creating sqlite in memory database" &#160;&#160;load "#{RAILS_ROOT}/db/schema.rb" # use db agnostic schema by default &#160;&#160;# ActiveRecord::Migrator.up('db/migrate') # use migrations end 不过要注意，以上代码最好加在”# Include your application configuration below”这一行之后，因为说不准后面的配置有可能就会用到数据库。 [...]<table class="wumii-related-items" cellspacing="0" cellpadding="3" border="0"  style="clear: both;">
    
    <tr>
        <td colspan="4"><b><font size="-1"  style="display: block !important; padding: 20px 0 5px !important;">无觅猜您也喜欢：</font></b></td>
    </tr>
    
        <tr>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important;">
                    <a target="_blank" title="使用Flog测试你的Ruby代码复杂度" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2F62%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2F55%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/site_images/2011/03/08/3251517.jpg" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">使用Flog测试你的Ruby代码复杂度</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="Rails Cookie测试" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fhow-to-test-rails-cookie%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2F55%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/images/blogWidget/wordpress_default.gif" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">Rails Cookie测试</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="rcov: ruby代码覆盖率工具" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2F51%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2F55%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/site_images/2011/03/08/3251581.png" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">rcov: ruby代码覆盖率工具</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="Bash提示符显示Git分支" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fshow-git-branch-in-bash-prompt%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2F55%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/site_images/2011/05/15/8702104.png" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">Bash提示符显示Git分支</font>
                    </a>
                </td>
        </tr>
    
    <tr>
        <td colspan="4" align="right">
            <a style="text-decoration: none !important;" href="http://www.wumii.com/widget/relatedItems.htm" target="_blank" title="无觅相关文章插件">
                <font size="-1" color="#bbbbbb" style="display: block !important; font-family: arial !important; padding: 5px 0 !important; font-size: 12px !important; color: #bbb !important;">无觅</font>
            </a>
        </td>
    </tr>
</table>]]></description>
			<content:encoded><![CDATA[<p><a href="http://lilac.greatweb.cn/rails/wp-admin/post-new.php">对于需要进行持续集成的大型项目来说，运行测试代码的花费就显得尤为重要，</a><a href="http://blog.seagul.co.uk/" title="Chris Roos" id="qlfp">Chris Roos</a>在<a href="http://blog.seagul.co.uk/articles/2006/02/08/in-memory-sqlite-database-for-rails-testing" title="这篇帖子里" id="di-q">这篇帖子里</a>介绍了一种通过使用SQLite数据库来 提高测试代码运行效率的方法。</p>
<p>首先你需要安装<a href="http://www.sqlite.org/download.html" title="SQLite3" id="yh2a">SQLite3</a>以及sqlite3-ruby gem，然后修改database.yml：</p>
<p class="code"><code class="ruby">test:<br />
adapter: sqlite3<br />
database: ":memory:"</code></p>
<p>但是这样有一个问题，由于SQLite数据库保存在内存中，因此必须在每次执行单元测试之前首先生成数据库的大纲，不过不用担心，<a href="http://blog.seagul.co.uk/" title="Chris Roos" id="qlfp">Chris Roos</a>已经提供了一段现成的代码，将它加到你的environment.rb就可以了：</p>
<p class="code"><code class="ruby"><br />
def in_memory_database?<br />
&nbsp;&nbsp;ENV["RAILS_ENV"] == "test" and<br />
&nbsp;&nbsp;ActiveRecord::Base.connection.class == ActiveRecord::ConnectionAdapters::SQLite3Adapter and<br />
&nbsp;&nbsp;Rails::Configuration.new.database_configuration['test']['database'] == ':memory:'<br />
end<br />
if in_memory_database?<br />
&nbsp;&nbsp;puts "creating sqlite in memory database"<br />
&nbsp;&nbsp;load "#{RAILS_ROOT}/db/schema.rb" # use db agnostic schema by default<br />
&nbsp;&nbsp;#  ActiveRecord::Migrator.up('db/migrate') # use migrations<br />
end</code></p>
<p>不过要注意，以上代码最好加在”# Include your application configuration below”这一行之后，因为说不准后面的配置有可能就会用到数据库。</p>
<p>这段代码使用db/schema.rb来初始化数据库，因此你最好先执行下面这条命令，以保证schema.rb与数据库保持同步(当然你也可以使用db:migrate)：</p>
<p class="code"><code class="ruby">rake db:migrate:dump</code></p>
<p>现在在执行下rake test，看看速度是不是快了不少，下面是我找的一个小测试程序的运行结果：</p>
<p>sqlite in memory:<br />
unit tests: 0.14s<br />
functional tests: 0.59s</p>
<p>mysql:<br />
unit tests: 1.16s<br />
functional tests: 1.81s</p>
<p>如果你觉得这样还是有些麻烦，不要紧，<a href="http://nubyonrails.com/">Geoffrey Grosenbach</a>已经为你准备好了一个<a href="http://nubyonrails.com/articles/2006/06/01/san-francisco-sqlite3-memory-tests-asteroids" title="插件" id="j44:">插件</a>，你只需要动手改一下database.yml就成了。</p>
<p><strong>更新：如果不想每次都看到那一堆数据库创建信息，那么只需在加载schema.rb之前，将ActiveRecord::Schema.verbose置为false即可：</strong></p>
<p class="code"><code class="ruby">if in_memory_database?<br />
&nbsp;&nbsp;verbose = ActiveRecord::Schema.verbose<br />
&nbsp;&nbsp;ActiveRecord::Schema.verbose = false<br />
&nbsp;&nbsp;puts "creating sqlite in memory database"<br />
&nbsp;&nbsp;load "#{RAILS_ROOT}/db/schema.rb" # use db agnostic schema by default<br />
&nbsp;&nbsp;ActiveRecord::Schema.verbose = verbose<br />
end</code></p>
<table class="wumii-related-items" cellspacing="0" cellpadding="3" border="0"  style="clear: both;">
    
    <tr>
        <td colspan="4"><b><font size="-1"  style="display: block !important; padding: 20px 0 5px !important;">无觅猜您也喜欢：</font></b></td>
    </tr>
    
        <tr>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important;">
                    <a target="_blank" title="使用Flog测试你的Ruby代码复杂度" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2F62%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2F55%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/site_images/2011/03/08/3251517.jpg" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">使用Flog测试你的Ruby代码复杂度</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="Rails Cookie测试" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fhow-to-test-rails-cookie%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2F55%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/images/blogWidget/wordpress_default.gif" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">Rails Cookie测试</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="rcov: ruby代码覆盖率工具" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2F51%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2F55%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/site_images/2011/03/08/3251581.png" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">rcov: ruby代码覆盖率工具</font>
                    </a>
                </td>
                <td width="102" valign="top" style="padding: 5px !important; margin: 0 !important; border-left: 1px solid #DDDDDD !important;">
                    <a target="_blank" title="Bash提示符显示Git分支" style="text-decoration: none !important; cursor: pointer !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fshow-git-branch-in-bash-prompt%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2F55%2F">
                        <img style="margin: 0 !important; padding: 2px !important; border: 1px solid #DDDDDD !important; width: 96px !important; height: 96px !important;" src="http://static.wumii.com/site_images/2011/05/15/8702104.png" width="96px" height="96px" /><br />
                        <font size="-1" color="#333333" style="display: block !important; line-height: 15px !important; width: 102px !important; font: 12px/15px arial !important; height: 60px !important; margin: 3px 0 0 0 !important; padding: 0 !important; overflow: hidden !important;">Bash提示符显示Git分支</font>
                    </a>
                </td>
        </tr>
    
    <tr>
        <td colspan="4" align="right">
            <a style="text-decoration: none !important;" href="http://www.wumii.com/widget/relatedItems.htm" target="_blank" title="无觅相关文章插件">
                <font size="-1" color="#bbbbbb" style="display: block !important; font-family: arial !important; padding: 5px 0 !important; font-size: 12px !important; color: #bbb !important;">无觅</font>
            </a>
        </td>
    </tr>
</table>]]></content:encoded>
			<wfw:commentRss>http://www.letrails.cn/archives/55/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>使用ruby-prof获取rails应用的profile</title>
		<link>http://www.letrails.cn/archives/36/</link>
		<comments>http://www.letrails.cn/archives/36/#comments</comments>
		<pubDate>Sat, 14 Jul 2007 14:36:14 +0000</pubDate>
		<dc:creator>Yuanyi ZHANG</dc:creator>
				<category><![CDATA[性能]]></category>
		<category><![CDATA[指南]]></category>

		<guid isPermaLink="false">http://www.letrails.cn/archives/36</guid>
		<description><![CDATA[ruby-prof最新的0.5版本开始支持Rails，但是文档并没有相应更新，这是来在Charlie Savage的一篇关于如何在Rails中使用ruby-prof的指南，希望对你有所帮助。 假设你发现你的Rails应用对某个请求的处理花费了太多的时间，并且你已经排除了网络，Web Server，客户端浏览器或者是数据库的嫌疑，那么ruby-prof可以帮你轻松定位出到底是那段代码消耗了太多的时间： gem install ruby-prof windows平台用户应该选择针对win32平台的预编译版本，安装完之后，你需要从ruby-prof的安装目录下拷贝plugin到你的Rails应用的vendor/plugins目录: cd /your/ruby/gems/path/ruby-prof-0.5.0/lib/ cp ruby-prof/rails_plugin/ruby_prof rails_app/vendor/plugins 然后在你的environment.rb中增加： config.cache_classes = true 如果不设置这一项的话，那么Rails会在处理每个请求时重新将所有的model和controller都加载一遍，这会消耗大量的时间，从而使你的action的花费看起来微不足道。 完成以上操作以后，如果现在你通过浏览器向Rails发送一个请求，那么在请求处理完成后，这个请求的profile已经被写入到了Log里面，它看起来是这个样子： Completed in 0.71900 (1 reqs/sec) Rendering: 0.37600 (52%) &#124; DB: 0.18700 (26%) 200 OK [http://localhost/] Thread ID: 175635930 Total: 0.719 %self total self wait child calls name 26.15 0.19 0.19 0.00 0.00 23 PGconn#exec 26.01 0.19 [...]<table class="wumii-related-items" cellspacing="0" cellpadding="2" border="0" width="100%" style="clear: both;">
    
    <tr>
        <td ><b><font size="-1"  style="display: block !important; padding: 20px 0 5px !important;">无觅猜您也喜欢：</font></b></td>
    </tr>
    
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fruby-rails-interview-questions%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2F36%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">如何采访Ruby/Rails大牛</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2F07-11-15-ibm-dw-launches-ruby-on-rails-resource-center%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2F36%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">IBM DW Ruby on Rails资源中心上线</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fupgrade-to-rails-3-beta%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2F36%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">升级到Rails 3 Beta</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fmake-theme-support-works-under-rails-2-1-0%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2F36%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">theme_support: 为Rails应用添加theme支持</font>
                    </a>
                </td>
            </tr>
    
    <tr>
        <td  align="right">
            <a style="text-decoration: none !important;" href="http://www.wumii.com/widget/relatedItems.htm" target="_blank" title="无觅相关文章插件">
                <font size="-1" color="#bbbbbb" style="display: block !important; font-family: arial !important; padding: 5px 0 !important; font-size: 12px !important; color: #bbb !important;">无觅</font>
            </a>
        </td>
    </tr>
</table>]]></description>
			<content:encoded><![CDATA[<p>ruby-prof最新的0.5版本开始支持Rails，但是文档并没有相应更新，这是来在<a href="http://cfis.savagexi.com/">Charlie Savage</a>的一篇关于<a href="http://cfis.savagexi.com/articles/2007/07/10/how-to-profile-your-rails-application">如何在Rails中使用ruby-prof的指南</a>，希望对你有所帮助。</p>
<p>假设你发现你的Rails应用对某个请求的处理花费了太多的时间，并且你已经排除了网络，Web Server，客户端浏览器或者是数据库的嫌疑，那么ruby-prof可以帮你轻松定位出到底是那段代码消耗了太多的时间：</p>
<p class="code"><code>gem install ruby-prof</code></p>
<p>windows平台用户应该选择针对win32平台的预编译版本，安装完之后，你需要从ruby-prof的安装目录下拷贝plugin到你的Rails应用的vendor/plugins目录:</p>
<p class="code"><code>cd /your/ruby/gems/path/ruby-prof-0.5.0/lib/<br />
cp ruby-prof/rails_plugin/ruby_prof rails_app/vendor/plugins</code></p>
<p>然后在你的environment.rb中增加：</p>
<p class="code"><code>config.cache_classes = true</code></p>
<p>如果不设置这一项的话，那么Rails会在处理每个请求时重新将所有的model和controller都加载一遍，这会消耗大量的时间，从而使你的action的花费看起来微不足道。</p>
<p>完成以上操作以后，如果现在你通过浏览器向Rails发送一个请求，那么在请求处理完成后，这个请求的profile已经被写入到了Log里面，它看起来是这个样子：</p>
<p class="code"><code>Completed in 0.71900 (1 reqs/sec)<br />
Rendering: 0.37600 (52%) | DB: 0.18700 (26%)<br />
200 OK [http://localhost/]<br />
Thread ID: 175635930<br />
Total: 0.719<br />
%self     total     self     wait    child    calls  name<br />
26.15      0.19     0.19     0.00     0.00       23  PGconn#exec<br />
26.01      0.19     0.19     0.00     0.00       27  PGresult#each<br />
4.45      0.03     0.03     0.00     0.00     1403  String#match<br />
4.45      0.03     0.03     0.00     0.00      171  IO#write<br />
2.23      0.02     0.02     0.00     0.00      872  String#to_s<br />
2.23      0.02     0.02     0.00     0.00      467  String#gsub<br />
2.23      0.03     0.02     0.00     0.02       76  ManyParser#_parse<br />
2.23      0.05     0.02     0.00     0.03       60  MonitorMixin#synchronize<br />
2.23      0.02     0.02     0.00     0.00       60  Parsers#sequence<br />
2.23      0.02     0.02     0.00     0.00     1640  ParseContext#eof<br />
2.23      0.02     0.02     0.00     0.00       31  ActionView::Partials#add_object_to_local_assigns!<br />
2.23      0.02     0.02     0.00     0.00       11  ActionView::Helpers::UrlHelper#link_to<br />
2.23      0.02     0.02     0.00     0.00      243  Object#add_error<br />
2.23      0.02     0.02     0.00     0.00      175  Kernel#clone</code></p>
<p>第一行显示了Rails处理这个请求的总花费，接下来就是ruby-prof的plat格式的输出，按照花费总时间由高到低排列，这里只列出了花费大于2%的部分。</p>
<p>从上面的结果可以看出，花费时间最多的是PGconn#exec，这是个连接数据库和执行查询的C扩展，在Rails这段并没有多少优化余地，但是在数据 库段还是存在优化空间的，接下来就是PGresult#each，这是处理数据库查询结果的，它的花费明显太多了，但是它后面的String#match 被执行了1403次，这也不太正常。</p>
<p>如果你觉得总是去Rails log中查看profile结果实在是不方便，那么可以通过Hack ruby-prof来获取图形化的输出，修改vendor/ruby-prof/lib/profiling.rb：</p>
<p class="code"><code class="ruby"> module ActionController #:nodoc:<br />
&nbsp;&nbsp; module Profiling #:nodoc:<br />
&nbsp;&nbsp;&nbsp;&nbsp; def perform_action_with_profiling<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if RubyProf.running? or<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ...<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; else<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ...<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; # Example for Graph html printer<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; printer = RubyProf::GraphHtmlPrinter.new(result)<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; File.open('request.html', 'w') do |file|<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; printer.print(file, {:min_percent =&gt; 1,<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; :print_file =&gt; true})<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; end<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; end<br />
&nbsp;&nbsp;&nbsp;&nbsp;end<br />
&nbsp;&nbsp;end<br />
end</code></p>
<p>现在再次执行上面的那个请求，ruby-prof已经创建了一个request.html的文件（windows下位于c:/temp/目录下):</p>
<p><img src="http://docs.google.com/File?id=ahxzccrw5xq_120ctwf3qgc" height="347" width="481" /></p>
<p>如果你以前没有使用过ruby-prof的graph格式，那么上面的输出可能会让你感到迷惑，不要紧，实际上，我们只需要关心粗体的那一行就够了，在它 上面是调用了它的函数的调用栈，下面则是它调用的函数，至于Array#each, Array#each-1, Array#each-2，它们后面的数字表示存在嵌套调用，数字用于指明嵌套的层次（也就是Array#each调用了Array#each-1， Array#each-1又调用了Array#each-2）。</p>
<p>从上图可以看出，Array#each-4调用了String#match最多次（380），因此我们下一步要做的就是追踪Array#each-4，看看到底谁调用了它。</p>
<p>如果你觉得上面的图对于追踪函数调用关系还是不够直观的话，还有办法，ruby-prof0.5提供了call tree格式的输出：</p>
<p class="code"><code class="ruby">module ActionController #:nodoc:<br />
&nbsp;&nbsp;module Profiling #:nodoc:<br />
&nbsp;&nbsp;&nbsp;&nbsp;def perform_action_with_profiling<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if RubyProf.running? or<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;...<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;else<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;...<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;# Example for Graph html printer<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; printer = RubyProf::CallTreePrinter.new(result)<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; File.open('callgrind.out', 'w') do |file|<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; printer.print(file, {:min_percent =&gt; 1,<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; :print_file =&gt; true})<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;end<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;end<br />
&nbsp;&nbsp;&nbsp;&nbsp;end<br />
&nbsp;&nbsp;end<br />
end</code></p>
<p>现在再次执行同样的请求，你将得到一个callgrind.out的文件，可以使用 KCachegrind (目前只支持Linux，Windows下的版本叫做WinCacheGrind)打开它：</p>
<p><a href="http://docs.google.com/File?id=ahxzccrw5xq_119f457z9fq"><img src="http://docs.google.com/File?id=ahxzccrw5xq_119f457z9fq" height="476" width="429" /></a></p>
<p>不过，需要注意的是，大多数情况下你并不需要一开始就使用ruby-prof，你可以先从web server log， rails log或者是database log入手，如果确定了问题确实是由于你的rails代码引起的，那么ruby-prof就该登场亮相了。</p>
<table class="wumii-related-items" cellspacing="0" cellpadding="2" border="0" width="100%" style="clear: both;">
    
    <tr>
        <td ><b><font size="-1"  style="display: block !important; padding: 20px 0 5px !important;">无觅猜您也喜欢：</font></b></td>
    </tr>
    
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fruby-rails-interview-questions%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2F36%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">如何采访Ruby/Rails大牛</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2F07-11-15-ibm-dw-launches-ruby-on-rails-resource-center%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2F36%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">IBM DW Ruby on Rails资源中心上线</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fupgrade-to-rails-3-beta%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2F36%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">升级到Rails 3 Beta</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fmake-theme-support-works-under-rails-2-1-0%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2F36%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">theme_support: 为Rails应用添加theme支持</font>
                    </a>
                </td>
            </tr>
    
    <tr>
        <td  align="right">
            <a style="text-decoration: none !important;" href="http://www.wumii.com/widget/relatedItems.htm" target="_blank" title="无觅相关文章插件">
                <font size="-1" color="#bbbbbb" style="display: block !important; font-family: arial !important; padding: 5px 0 !important; font-size: 12px !important; color: #bbb !important;">无觅</font>
            </a>
        </td>
    </tr>
</table>]]></content:encoded>
			<wfw:commentRss>http://www.letrails.cn/archives/36/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Rails应用性能优化4</title>
		<link>http://www.letrails.cn/archives/17/</link>
		<comments>http://www.letrails.cn/archives/17/#comments</comments>
		<pubDate>Wed, 13 Jun 2007 16:25:37 +0000</pubDate>
		<dc:creator>Yuanyi ZHANG</dc:creator>
				<category><![CDATA[性能]]></category>

		<guid isPermaLink="false">http://www.letrails.cn/archives/17</guid>
		<description><![CDATA[上一讲我们讲解了如何通过优化Ruby代码来提升我们的Rails应用性能，这一讲，让我们更深入一些，先看看Ruby的内存管理和垃圾回收机制。 首先，由于Ruby最初的设计目标是成为像Perl那样的批处理语言，因此它的内存管理机制并没有针对Rails这样的需要长期运行的服务端程序进行最优化，有些地方甚至是背道而驰： Rails的内存管理策略是尽量减少内存占用 标记和清除算法十分简单 使用malloc来分配连续的内存块（Ruby heap） 复杂的数据结构 C扩展十分容易编写，但是当前的C接口很难实现generational GC（Ruby2有可能） Ruby的垃圾回收机制对于Rails也不是最优的，由于Ruby的AST（抽象语法树）存储在堆上，并且在每次GC时都会被扫描一遍，而这恰恰是Rails中最大的一块非垃圾区，也就是说，GC对于Rails做的大部分工作都是做无用功。 并且，Ruby的清除算法依赖于堆的大小，而不是当前非垃圾区的大小，但是堆的增长存在一定限制，只有当进行GC后，当前的freelist &#60; FREE_MIN，堆才会增加，gc.c中定义的增加值为4096，这对于Rails来说明显太小了，堆应该至少能够容纳20万个对象。 要提高Ruby GC的性能，可以在Rails dispatcher中添加如下语句： # excerpt from dispatch. fcgi RailsFCGIHandler.process! nil, 50 这句话将禁止Ruby GC运行，在处理50个请求后再启用GC，但是这个方法存在一个问题，它没法区分小请求和大请求，这有可能会导致： 堆变的过大 小页面的性能会受损 Ruby will still deallocate heap blocks if empty after GC（这句不是很理解，上原文） 除了控制GC的运行时机，也可以通过修改GC的参数来提升性能，但需要先给GC打补丁，下载最新的railsbench，打上rubygc.patch补丁，然后重新编译并安装Ruby，就可以通过以下参数对GC进行调整了： RUBY_HEAP_MIN_SLOTS, 初始堆大小，默认10000 RUBY HEAP FREE MIN，GC后可用的heap slot的最小值，默认4096 RUBY GC MALLOC LIMIT，允许不触发GC而分配的C数据结构的最大值（字节为单位），默认8,000,000 我们的推荐值为： RUBY_HEAP_MIN_SLOTS = 600000 RUBY_GC_MALLOC_LIMIT [...]<table class="wumii-related-items" cellspacing="0" cellpadding="2" border="0" width="100%" style="clear: both;">
    
    <tr>
        <td ><b><font size="-1"  style="display: block !important; padding: 20px 0 5px !important;">无觅猜您也喜欢：</font></b></td>
    </tr>
    
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fupgrade-to-rails-3-beta%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2F17%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">升级到Rails 3 Beta</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Frails-performance-optimization-guide%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2F17%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">Rails性能优化简明指南</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fxapian-vs-sphinx-in-rails%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2F17%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">Xapian，Sphinx在Rails中的性能比较</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fusing-rails-reviewer-analytize-rails-performance%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2F17%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">使用rails_reviewer优化Rails数据库查询性能</font>
                    </a>
                </td>
            </tr>
    
    <tr>
        <td  align="right">
            <a style="text-decoration: none !important;" href="http://www.wumii.com/widget/relatedItems.htm" target="_blank" title="无觅相关文章插件">
                <font size="-1" color="#bbbbbb" style="display: block !important; font-family: arial !important; padding: 5px 0 !important; font-size: 12px !important; color: #bbb !important;">无觅</font>
            </a>
        </td>
    </tr>
</table>]]></description>
			<content:encoded><![CDATA[<p>上一讲我们讲解了如何通过优化Ruby代码来提升我们的Rails应用性能，这一讲，让我们更深入一些，先看看Ruby的内存管理和垃圾回收机制。</p>
<p>首先，由于Ruby最初的设计目标是成为像Perl那样的批处理语言，因此它的内存管理机制并没有针对Rails这样的需要长期运行的服务端程序进行最优化，有些地方甚至是背道而驰：</p>
<ul>
<li>Rails的内存管理策略是尽量减少内存占用</li>
<li>标记和清除算法十分简单</li>
<li>使用malloc来分配连续的内存块（Ruby heap）</li>
<li>复杂的数据结构</li>
<li>C扩展十分容易编写，但是当前的C接口很难实现generational GC（Ruby2有可能）</li>
</ul>
<p>Ruby的垃圾回收机制对于Rails也不是最优的，由于Ruby的AST（抽象语法树）存储在堆上，并且在每次GC时都会被扫描一遍，而这恰恰是Rails中最大的一块非垃圾区，也就是说，GC对于Rails做的大部分工作都是做无用功。</p>
<p>并且，Ruby的清除算法依赖于堆的大小，而不是当前非垃圾区的大小，但是堆的增长存在一定限制，只有当进行GC后，当前的freelist &lt; FREE_MIN，堆才会增加，gc.c中定义的增加值为4096，这对于Rails来说明显太小了，堆应该至少能够容纳20万个对象。</p>
<p>要提高Ruby GC的性能，可以在Rails dispatcher中添加如下语句：</p>
<p class="code"><code class="ruby"># excerpt from dispatch. fcgi<br />
RailsFCGIHandler.process! nil, 50</code></p>
<p>这句话将禁止Ruby GC运行，在处理50个请求后再启用GC，但是这个方法存在一个问题，它没法区分小请求和大请求，这有可能会导致：</p>
<ul>
<li>堆变的过大</li>
<li>小页面的性能会受损</li>
<li>Ruby will still deallocate heap blocks if empty after GC（这句不是很理解，上原文）</li>
</ul>
<p>除了控制GC的运行时机，也可以通过修改GC的参数来提升性能，但需要先给GC打补丁，下载最新的railsbench，打上rubygc.patch补丁，然后重新编译并安装Ruby，就可以通过以下参数对GC进行调整了：</p>
<ul>
<li>RUBY_HEAP_MIN_SLOTS, 初始堆大小，默认10000</li>
<li>RUBY HEAP FREE MIN，GC后可用的heap slot的最小值，默认4096</li>
<li>RUBY GC MALLOC LIMIT，允许不触发GC而分配的C数据结构的最大值（字节为单位），默认8,000,000</li>
</ul>
<p>我们的推荐值为：</p>
<p class="code"><code>RUBY_HEAP_MIN_SLOTS = 600000<br />
RUBY_GC_MALLOC_LIMIT = 60000000<br />
RUBY_HEAP_FREE_MIN = 100000</code></p>
<p>如果你进行基准测试的话，就会发现性能提高不少。</p>
<p>最后，我们再讲讲模板优化，对于许多在编译时就知道结果的helper方法，完全没有必要在每次处理请求时都进行解析，比如：</p>
<p class="code"><code class="ruby">&lt;%= end_form_tag %&gt; ===&gt; &lt;/form&gt;</code></p>
<p>这纯粹就是浪费时间，还有我们前面提到的link_to，因此，如果我们可以在敲代码时确定这个helper的输出，那么最好直接写出结果。</p>
<p>另外，还可以使用Ryan Davis的ParseTree和ruby2ruby来获取ActionView的render方法的AST，并进行模板终极优化：</p>
<ul>
<li>展开所有helper方法</li>
<li>去除不会调用到的代码</li>
<li>去除不会用到的变量（以及partials）</li>
<li>合并hash</li>
<li>替换常量</li>
<li>替换结果已确定的方法调用</li>
<li>替换符号</li>
</ul>
<p>然后使用eval将新的AST编译入优化后的render方法。</p>
<p>好了，到这里，这一系列的文章就结束了，附录中还有一些性能测试的数据和配置信息，就不一一列举了，感兴趣的可以<a href="https://railsexpress.de/blog/files/slides/railsconf2006.pdf">下载原文</a>查看。</p>
<table class="wumii-related-items" cellspacing="0" cellpadding="2" border="0" width="100%" style="clear: both;">
    
    <tr>
        <td ><b><font size="-1"  style="display: block !important; padding: 20px 0 5px !important;">无觅猜您也喜欢：</font></b></td>
    </tr>
    
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fupgrade-to-rails-3-beta%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2F17%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">升级到Rails 3 Beta</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Frails-performance-optimization-guide%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2F17%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">Rails性能优化简明指南</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fxapian-vs-sphinx-in-rails%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2F17%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">Xapian，Sphinx在Rails中的性能比较</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fusing-rails-reviewer-analytize-rails-performance%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2F17%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">使用rails_reviewer优化Rails数据库查询性能</font>
                    </a>
                </td>
            </tr>
    
    <tr>
        <td  align="right">
            <a style="text-decoration: none !important;" href="http://www.wumii.com/widget/relatedItems.htm" target="_blank" title="无觅相关文章插件">
                <font size="-1" color="#bbbbbb" style="display: block !important; font-family: arial !important; padding: 5px 0 !important; font-size: 12px !important; color: #bbb !important;">无觅</font>
            </a>
        </td>
    </tr>
</table>]]></content:encoded>
			<wfw:commentRss>http://www.letrails.cn/archives/17/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Rails应用性能优化3</title>
		<link>http://www.letrails.cn/archives/16/</link>
		<comments>http://www.letrails.cn/archives/16/#comments</comments>
		<pubDate>Tue, 12 Jun 2007 14:52:12 +0000</pubDate>
		<dc:creator>Yuanyi ZHANG</dc:creator>
				<category><![CDATA[性能]]></category>

		<guid isPermaLink="false">http://www.letrails.cn/archives/16</guid>
		<description><![CDATA[上一讲，我们的优化策略主要是针对Rails框架进行，这一讲，我们将精力集中到Ruby语言本身。 首先，Ruby语言中的各种元素由于算法的不同，访问时间也各不相等，比如局部变量采用数组索引，在解析时进行顶问，因此访问代价总是O(1)，而实例变量和和方法调用由于使用Hash访问，因此只能保持理论上的O(1)访问，也就是没有冲突的情况下，同时调用方法时如果不能在子类找到这个方法，则还需要沿继承树向上回溯查找。 因此，应该尽量避免不必要的多态继承，同时应该尽量使用局部变量，比如下面这段代码的效率就不如修改后的高： def submit to remote(name, value, options = {}) &#160;&#160;options[ :with ] &#124;&#124;= ’Form.serialize( this .form)’ &#160;&#160;options[:html ] &#124;&#124;= {} &#160;&#160;options[:html ][ :type ] = ’button’ &#160;&#160;options[:html ][ nclick ] = ”#{remote function(options)}; return false ; ” &#160;&#160;options[:html ][ :name] = name &#160;&#160;options[:html ][ :value] = value &#160;&#160;tag(”input” , options[:html ], false ) [...]<table class="wumii-related-items" cellspacing="0" cellpadding="2" border="0" width="100%" style="clear: both;">
    
    <tr>
        <td ><b><font size="-1"  style="display: block !important; padding: 20px 0 5px !important;">无觅猜您也喜欢：</font></b></td>
    </tr>
    
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Frails-performance-optimization-guide%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2F16%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">Rails性能优化简明指南</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fusing-rails-reviewer-analytize-rails-performance%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2F16%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">使用rails_reviewer优化Rails数据库查询性能</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fupgrade-to-rails-3-beta%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2F16%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">升级到Rails 3 Beta</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fxapian-vs-sphinx-in-rails%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2F16%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">Xapian，Sphinx在Rails中的性能比较</font>
                    </a>
                </td>
            </tr>
    
    <tr>
        <td  align="right">
            <a style="text-decoration: none !important;" href="http://www.wumii.com/widget/relatedItems.htm" target="_blank" title="无觅相关文章插件">
                <font size="-1" color="#bbbbbb" style="display: block !important; font-family: arial !important; padding: 5px 0 !important; font-size: 12px !important; color: #bbb !important;">无觅</font>
            </a>
        </td>
    </tr>
</table>]]></description>
			<content:encoded><![CDATA[<p>上一讲，我们的优化策略主要是针对Rails框架进行，这一讲，我们将精力集中到Ruby语言本身。</p>
<p>首先，Ruby语言中的各种元素由于算法的不同，访问时间也各不相等，比如局部变量采用数组索引，在解析时进行顶问，因此访问代价总是O(1)，而实例变量和和方法调用由于使用Hash访问，因此只能保持理论上的O(1)访问，也就是没有冲突的情况下，同时调用方法时如果不能在子类找到这个方法，则还需要沿继承树向上回溯查找。</p>
<p>因此，应该尽量避免不必要的多态继承，同时应该尽量使用局部变量，比如下面这段代码的效率就不如修改后的高：</p>
<p class="code"><code class="ruby">def submit to remote(name, value, options = {})<br />
&nbsp;&nbsp;options[ :with ] ||= ’Form.serialize( this .form)’<br />
&nbsp;&nbsp;options[:html ] ||= {}<br />
&nbsp;&nbsp;options[:html ][ :type ] = ’button’<br />
&nbsp;&nbsp;options[:html ][ <img src='http://www.letrails.cn/wp-includes/images/smilies/icon_surprised.gif' alt=':o' class='wp-smiley' /> nclick ] = ”#{remote function(options)}; return false ; ”<br />
&nbsp;&nbsp;options[:html ][ :name] = name<br />
&nbsp;&nbsp;options[:html ][ :value] = value<br />
&nbsp;&nbsp;tag(”input” , options[:html ], false )<br />
end</code></p>
<p>修改后：</p>
<p class="code"><code class="ruby">def submit to remote(name, value, options = {})<br />
&nbsp;&nbsp;options[ :with ] ||= ’Form.serialize( this .form)’<br />
&nbsp;&nbsp;html = (options[:html ] ||= {})<br />
&nbsp;&nbsp;html[:type ] = ’button’<br />
&nbsp;&nbsp;html[ <img src='http://www.letrails.cn/wp-includes/images/smilies/icon_surprised.gif' alt=':o' class='wp-smiley' /> nclick ] = ”#{remote function(options)}; return false ; ”<br />
&nbsp;&nbsp;html[:name] = name<br />
&nbsp;&nbsp;html[:value] = value<br />
&nbsp;&nbsp;tag(”input” , html, false )<br />
end</code></p>
<p>其次，对于经常用到的数据，应该进行缓存，避免每次用到时再进行计算，比如：</p>
<p class="code"><code class="ruby">def capital_letters<br />
&nbsp;&nbsp;( ”A” .. ”Z” ). to a<br />
end</code></p>
<p>写成下面这样会更好：</p>
<p class="code"><code class="ruby">def capital letters<br />
&nbsp;&nbsp;@capital letters ||= ( ”A” .. ”Z” ). to a<br />
end</code></p>
<p>当然对于上面这种情况，如果所有类需要的数据都相同，那么完全可以将它定义成class级变量：</p>
<p class="code"><code class="ruby">@@capital letters = (”A” .. ”Z” ). to a<br />
def capital letters<br />
&nbsp;&nbsp;@@capital letters<br />
end</code></p>
<p>当然，除了效率也要注意优美，下面这段代码就不够优美：</p>
<p class="code"><code class="ruby">def actions<br />
&nbsp;&nbsp;unless @actions<br />
&nbsp;&nbsp;&nbsp;&nbsp;# do something complicated and costly to determine action’s value<br />
&nbsp;&nbsp;&nbsp;&nbsp;@actions = expr<br />
&nbsp;&nbsp;end<br />
&nbsp;&nbsp;@actions<br />
end</code></p>
<p>改成这样会更好一些：</p>
<p class="code"><code class="ruby">def actions<br />
&nbsp;&nbsp;@actions ||=<br />
&nbsp;&nbsp;begin<br />
&nbsp;&nbsp;&nbsp;&nbsp;# do something complicated and costly to determine action’s value<br />
&nbsp;&nbsp;&nbsp;&nbsp;expr<br />
&nbsp;&nbsp;end<br />
end</code></p>
<p>另外，使用常量对效率也有一定提升。</p>
<p class="code"><code class="ruby">def validate_find_options (options)<br />
&nbsp;&nbsp;options.assert valid keys( :conditions , :include , :joins , :limit , <img src='http://www.letrails.cn/wp-includes/images/smilies/icon_surprised.gif' alt=':o' class='wp-smiley' /> ffset ,<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;:order , :select , :readonly, :group, :from )<br />
end</code></p>
<p>上面这段代码进行如下修改会更好一些:</p>
<p class="code"><code class="ruby">VALID FIND OPTIONS = [<br />
&nbsp;&nbsp;&nbsp;&nbsp;:conditions , :include , :joins , :limit ,<br />
&nbsp;&nbsp;&nbsp;&nbsp;:offset , <img src='http://www.letrails.cn/wp-includes/images/smilies/icon_surprised.gif' alt=':o' class='wp-smiley' /> rder , :select , :readonly, :group, :from ]<br />
def validate find options (options)<br />
&nbsp;&nbsp;options.assert valid keys(VALID FIND OPTIONS)<br />
end</code></p>
<p>同时，应该尽可能的使用局部变量。</p>
<p class="code"><code class="ruby">sql << ” GROUP BY #{options[:group]} ” if options[:group]</code></p>
<p>上面这种方式明显不如以下两种：</p>
<p class="code"><code class="ruby">if opts = options[:group]<br />
&nbsp;&nbsp;sql << ” GROUP BY #{opts} ”<br />
end</code></p>
<p class="code"><code class="ruby">opts = options[:group] and sql << ” GROUP BY #{opts} ”</code></p>
<p>当然，能够写成这样是最好的：</p>
<p class="code"><code class="ruby">sql << ” GROUP BY #{opts} ” if opts = options[:group]</code></p>
<p>但是语法不支持。</p>
<p>还有一些小技巧：</p>
<p class="code"><code class="ruby">logger.debug ”args: #{hash.keys.sort.join ( ’ ’ )}” if logger</code></p>
<p>这段代码的问题在于，不管logger.level是否为DEBUG，hash.keys.sort.join(’ ’) 都会被执行，因此，应该写成这样:</p>
<p class="code"><code class="ruby">logger.debug ”args: #{hash.keys.sort.join ( ’ ’ )}” if logger &#038;&#038; logger.debug?</code></p>
<p>还有就是关于ObjectSpace.each_object的，在production模式最好不要使用这个方法。</p>
<p class="code"><code class="ruby">ObjectSpace.each object(Class) {|c| f(c) }</code></p>
<p>事实上跟下面的代码是相等的：</p>
<p class="code"><code class="ruby">ObjectSpace.each object {|o| o.is a?(Class) &#038;&#038; f(o) }</code></p>
<p>它会对堆上的每一个对象都进行检查，这会对性能造成极大损耗。</p>
<p>好了，关于Ruby语言的优化技巧就这么多了，下一讲我们将对Ruby的垃圾回收（GC）机制进行分析，并给出相应的优化策略。</p>
<table class="wumii-related-items" cellspacing="0" cellpadding="2" border="0" width="100%" style="clear: both;">
    
    <tr>
        <td ><b><font size="-1"  style="display: block !important; padding: 20px 0 5px !important;">无觅猜您也喜欢：</font></b></td>
    </tr>
    
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Frails-performance-optimization-guide%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2F16%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">Rails性能优化简明指南</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fusing-rails-reviewer-analytize-rails-performance%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2F16%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">使用rails_reviewer优化Rails数据库查询性能</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fupgrade-to-rails-3-beta%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2F16%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">升级到Rails 3 Beta</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fxapian-vs-sphinx-in-rails%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2F16%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">Xapian，Sphinx在Rails中的性能比较</font>
                    </a>
                </td>
            </tr>
    
    <tr>
        <td  align="right">
            <a style="text-decoration: none !important;" href="http://www.wumii.com/widget/relatedItems.htm" target="_blank" title="无觅相关文章插件">
                <font size="-1" color="#bbbbbb" style="display: block !important; font-family: arial !important; padding: 5px 0 !important; font-size: 12px !important; color: #bbb !important;">无觅</font>
            </a>
        </td>
    </tr>
</table>]]></content:encoded>
			<wfw:commentRss>http://www.letrails.cn/archives/16/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Rails应用性能优化2</title>
		<link>http://www.letrails.cn/archives/13/</link>
		<comments>http://www.letrails.cn/archives/13/#comments</comments>
		<pubDate>Mon, 11 Jun 2007 12:33:28 +0000</pubDate>
		<dc:creator>Yuanyi ZHANG</dc:creator>
				<category><![CDATA[性能]]></category>

		<guid isPermaLink="false">http://www.letrails.cn/archives/13</guid>
		<description><![CDATA[在开始之前，有一点需要说明，优化策略事实上大部分情况下都不具备通用性，因为软硬件差异，用户使用习惯等等原因，可能会造成同一条优化策略在不同系统中 得到完全不同的效果，当然这里讲的都是一些具有普遍适用性的策略，但我还是建议你在应用这些策略时进行一下对比测试，就像第一讲开头所说，不要盲目优化。 Session优化 如果你的系统需要为每个访问者保存单独的Session信息（比如购物网站），那么session的存取速度将是影响系统性能的关键因素，目前可用的session存取策略有： 内存，快，相当快！但是如果你的应用挂了，或者由于其它什么原因需要重启，那么所有的session信息都会丢失，并且这种方式仅仅只能在单APP Server的应用中使用 文件系统，很容易使用，每个session对应一个文件，并且可以通过NFS或者NAS轻松进行容量扩展，但是速度较慢 数据库/ActiveRecordStore，使用简单（Rails的默认策略），但是很慢 数据库/SQLSessionStore，与上面一种方式类似，但是使用原始SQL取代了ActiveRecord，性能有一定提升，关于SQLSessionStore与ActiveRecordStore的对比可以参看这篇文章 memcached，比SQLSessionStore稍微快一些，可扩展性较好，但是较难获取统计信息，关于memcached与SQLSessionStore的对比，请参看这篇文章 DrbStore，在memcached不支持的一些平台上，可以选择DrbStore，但是性能比memcached要差一些，并且不支持session自动清除。 Cache优化 Rails默认支持一下集中Cache方式： Pages，很快，整个页面都被保存在文件系统，Web Server可以直接绕过APP Server完成请求应答，但是存在一些固有缺陷，比如无法应付需要用户登录的应用 Actions，第二快，缓存controller的action执行结果，同时由于可以调用到controller的过滤器，因此可以很好的防止未授权用户访问。 Fragment，缓存请求结果的一部分，也可以感知用户是否登录 Action Cache事实上是Fragment Cache的一种特殊情况，跟session一样cache也有以下集中存取策略可供选择： 内存，最快的方式，如果你的程序只需要在一个APP Server上运行，那么这无疑是最好的方式 文件系统，一般快，但可以使用正则表达式来刷新过期页面 DrbStore，同文件系统相比，刷新过期页面更为快一些 memcached，比DrbStore更快且易于扩展，但不支持使用正则刷新过期页面 ActionController 使用Components会对ActionController的性能造成较大的影响，我的建议是没有特别的理由，不要使用 components，因为调用render_component会引发一个新的请求处理循环，大部分情况下，component都可以使用helper 或者partials代替。 ActionView 对于每一个请求，Rails都会创建一个controller和view实例，并会将controller的action中创建的实例变量通过 instance_variable_get和instance_variable_set传递给view，因此不要在action中创建view中用不 到的实例变量 helper优化 首先是pluralize，可以看一下pluralize的实现，如果不给出最后一个参数，它会创建一个Inflector实例，因此不要写pluralize(n, &#8216;post&#8217;)，应该写成pluralize(n, &#8216;post&#8217;, &#8216;posts&#8217;) 其次是link_to与url_for，由于需要查找路由策略，因此link_to与url_for可以说是最慢的helper方法，没有特别的需要，不要使用这两个函数。 &#60;a href="/recipe/edit/&#60;%=#{recipe.id}%&#62;" class="edit_link"&#62; look here for something interesting &#60;/a&#62; 会比下面这段快许多： &#60;%= link to ”look here [...]<table class="wumii-related-items" cellspacing="0" cellpadding="2" border="0" width="100%" style="clear: both;">
    
    <tr>
        <td ><b><font size="-1"  style="display: block !important; padding: 20px 0 5px !important;">无觅猜您也喜欢：</font></b></td>
    </tr>
    
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Frails-performance-optimization-guide%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2F13%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">Rails性能优化简明指南</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fupgrade-to-rails-3-beta%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2F13%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">升级到Rails 3 Beta</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fusing-rails-reviewer-analytize-rails-performance%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2F13%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">使用rails_reviewer优化Rails数据库查询性能</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fxapian-vs-sphinx-in-rails%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2F13%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">Xapian，Sphinx在Rails中的性能比较</font>
                    </a>
                </td>
            </tr>
    
    <tr>
        <td  align="right">
            <a style="text-decoration: none !important;" href="http://www.wumii.com/widget/relatedItems.htm" target="_blank" title="无觅相关文章插件">
                <font size="-1" color="#bbbbbb" style="display: block !important; font-family: arial !important; padding: 5px 0 !important; font-size: 12px !important; color: #bbb !important;">无觅</font>
            </a>
        </td>
    </tr>
</table>]]></description>
			<content:encoded><![CDATA[<p>在开始之前，有一点需要说明，优化策略事实上大部分情况下都不具备通用性，因为软硬件差异，用户使用习惯等等原因，可能会造成同一条优化策略在不同系统中 得到完全不同的效果，当然这里讲的都是一些具有普遍适用性的策略，但我还是建议你在应用这些策略时进行一下对比测试，就像第一讲开头所说，不要盲目优化。</p>
<p><strong><font size="5">Session优化</font></strong></p>
<p>如果你的系统需要为每个访问者保存单独的Session信息（比如购物网站），那么session的存取速度将是影响系统性能的关键因素，目前可用的session存取策略有：</p>
<ul>
<li>内存，快，相当快！但是如果你的应用挂了，或者由于其它什么原因需要重启，那么所有的session信息都会丢失，并且这种方式仅仅只能在单APP Server的应用中使用</li>
<li>文件系统，很容易使用，每个session对应一个文件，并且可以通过NFS或者NAS轻松进行容量扩展，但是速度较慢</li>
<li>数据库/ActiveRecordStore，使用简单（Rails的默认策略），但是很慢</li>
<li>数据库/SQLSessionStore，与上面一种方式类似，但是使用原始SQL取代了ActiveRecord，性能有一定提升，关于SQLSessionStore与ActiveRecordStore的对比可以参看<a href="http://railsexpress.de/blog/articles/2005/12/19/roll-your-own-sql-session-store" title="http://railsexpress.de/blog/articles/2005/12/19/roll-your-own-sql-session-store">这篇文章</a></li>
<li>memcached，比SQLSessionStore稍微快一些，可扩展性较好，但是较难获取统计信息，关于memcached与SQLSessionStore的对比，请参看<a href="http://railsexpress.de/blog/articles/2006/01/24/using-memcached-for-ruby-on-rails-session-storage" title="http://railsexpress.de/blog/articles/2006/01/24/using-memcached-for-ruby-on-rails-session-storage">这篇文章</a></li>
<li>DrbStore，在memcached不支持的一些平台上，可以选择DrbStore，但是性能比memcached要差一些，并且不支持session自动清除。</li>
</ul>
<p><font size="5"><strong>Cache优化</strong></font></p>
<p>Rails默认支持一下集中Cache方式：</p>
<ul>
<li>Pages，很快，整个页面都被保存在文件系统，Web Server可以直接绕过APP Server完成请求应答，但是存在一些固有缺陷，比如无法应付需要用户登录的应用</li>
<li>Actions，第二快，缓存controller的action执行结果，同时由于可以调用到controller的过滤器，因此可以很好的防止未授权用户访问。</li>
<li>Fragment，缓存请求结果的一部分，也可以感知用户是否登录</li>
</ul>
<p>Action Cache事实上是Fragment Cache的一种特殊情况，跟session一样cache也有以下集中存取策略可供选择：</p>
<ul>
<li>内存，最快的方式，如果你的程序只需要在一个APP Server上运行，那么这无疑是最好的方式</li>
<li>文件系统，一般快，但可以使用正则表达式来刷新过期页面</li>
<li>DrbStore，同文件系统相比，刷新过期页面更为快一些</li>
<li>memcached，比DrbStore更快且易于扩展，但不支持使用正则刷新过期页面</li>
</ul>
<p><strong><font size="5">ActionController</font></strong></p>
<p>使用Components会对ActionController的性能造成较大的影响，我的建议是没有特别的理由，不要使用 components，因为调用render_component会引发一个新的请求处理循环，大部分情况下，component都可以使用helper 或者partials代替。</p>
<p><strong><font size="5">ActionView</font></strong></p>
<p>对于每一个请求，Rails都会创建一个controller和view实例，并会将controller的action中创建的实例变量通过 instance_variable_get和instance_variable_set传递给view，因此不要在action中创建view中用不 到的实例变量</p>
<p><strong><font size="5">helper优化</font></strong></p>
<p>首先是pluralize，可以看一下pluralize的实现，如果不给出最后一个参数，它会创建一个<span class="ruby-constant">Inflector实例，因此不要写pluralize(n, &#8216;post&#8217;)，应该写成pluralize(n, &#8216;post&#8217;, &#8216;posts&#8217;)</span><span class="ruby-constant"></span></p>
<p><span class="ruby-constant">其次是link_to与url_for，由于需要查找路由策略，因此link_to与url_for可以说是最慢的helper方法，没有特别的需要，不要使用这两个函数。</span></p>
<p class="code"><code class="ruby">&lt;a href="/recipe/edit/&lt;%=#{recipe.id}%&gt;" class="edit_link"&gt;<br />
look here for something interesting<br />
&lt;/a&gt;</code></p>
<p>会比下面这段快许多：</p>
<p class="code"><code class="ruby">&lt;%= link to ”look here for something interesting” ,<br />
{ :controller =&gt; ”recipe”, :action =&gt; edit, :id =&gt; @recipe.id },<br />
{ :class =&gt; ” edit link ” } %&gt;</code></p>
<p><strong><font size="5">ActiveRecord</font></strong></p>
<p>访问AR对象的关联对象相对而言会比较慢，可以使用:include提前获取关联对象</p>
<p class="code"><code class="ruby">class Article<br />
&nbsp;&nbsp;belongs to :author<br />
end<br />
Article . find ( :all , :include =&gt; :author)</code></p>
<p>或者使用piggy backing指定要获取的关联对象的某些字段，关于piggy backing的介绍请参看<a href="http://railsexpress.de/blog/articles/2006/05/29/simpler-piggy-backing" title="http://railsexpress.de/blog/articles/2006/05/29/simpler-piggy-backing">这篇文章</a></p>
<p class="code"><code class="ruby">class Article<br />
&nbsp;&nbsp;piggy back :author name, :from =&gt; :author, :attributes =&gt; [:name]<br />
end<br />
article = Article . find ( :all , :piggy =&gt; :author)<br />
puts article .author name</code></p>
<p>另外需要注意的是，从数据库中获取的字段值一般来说都是String类型，因此每次访问可能都需要进行类型转换，如果你在一个请求处理过程中需要进行多次转换，那么最好对转换后的值进行缓存。</p>
<p>还有，根据我对一个应用的分析，大约有30%的时间花在了字符处理上，另外30%时间花在了垃圾收集，还有10%用于URL识别，因此在数据库中缓存格式化后的字段可以大大减小字符处理的开销。</p>
<p>这一讲就先到这里，更多的优化技巧，请关注后续文章。</p>
<table class="wumii-related-items" cellspacing="0" cellpadding="2" border="0" width="100%" style="clear: both;">
    
    <tr>
        <td ><b><font size="-1"  style="display: block !important; padding: 20px 0 5px !important;">无觅猜您也喜欢：</font></b></td>
    </tr>
    
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Frails-performance-optimization-guide%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2F13%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">Rails性能优化简明指南</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fupgrade-to-rails-3-beta%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2F13%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">升级到Rails 3 Beta</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fusing-rails-reviewer-analytize-rails-performance%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2F13%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">使用rails_reviewer优化Rails数据库查询性能</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fxapian-vs-sphinx-in-rails%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2F13%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">Xapian，Sphinx在Rails中的性能比较</font>
                    </a>
                </td>
            </tr>
    
    <tr>
        <td  align="right">
            <a style="text-decoration: none !important;" href="http://www.wumii.com/widget/relatedItems.htm" target="_blank" title="无觅相关文章插件">
                <font size="-1" color="#bbbbbb" style="display: block !important; font-family: arial !important; padding: 5px 0 !important; font-size: 12px !important; color: #bbb !important;">无觅</font>
            </a>
        </td>
    </tr>
</table>]]></content:encoded>
			<wfw:commentRss>http://www.letrails.cn/archives/13/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Rails应用性能优化1</title>
		<link>http://www.letrails.cn/archives/12/</link>
		<comments>http://www.letrails.cn/archives/12/#comments</comments>
		<pubDate>Sun, 10 Jun 2007 16:26:28 +0000</pubDate>
		<dc:creator>Yuanyi ZHANG</dc:creator>
				<category><![CDATA[性能]]></category>

		<guid isPermaLink="false">http://www.letrails.cn/archives/12</guid>
		<description><![CDATA[是否觉得你的Rails应用响应速度过于缓慢呢？这是RailsConf2006上的一篇关于Rails应用性能优化的演讲稿，希望能够对你有所帮助。 在优化你的应用之前，我们首先需要明确以下几点： 不先进行性能测试就盲目的优化是非常愚蠢的 如果你的应用是因为设计不合理而导致性能低下，那么我建议你最好花点时间重构你的代码，而不是进行局部的优化，这只会使问题越来越多。 在优化之前，最好先为自己树立一个目标，这样可以防止因为过度优化而浪费时间，达到预期的目标后就该适可而止 没有必要对每一个页面都进行优化，只需要关注那些最经常被访问的页面就可以了， 在开发期间，进行持续的性能测量，这样有助于你在优化时定位性能瓶颈。 在优化完成后，要评估我们优化的质量，我们就需要先确定一组性能参数： 延迟，响应一个请求需要多少时间 吞吐量，每秒最多可以处理多少个请求 系统利用率，在大量请求需要处理的时候，你的系统在满负荷运转吗？ 资源开销，在每个请求上所花费的开销 确定了要测量的性能参数，我们需要自动化的基准（benchmark）工具来帮我们进行优化前后的性能对比： Rails日志文件（debug_level &#62;= Logger::DEBUG) Rails日志分析工具（需要将日志输出到syslog） Rails基准脚本（script/benchmarker） 数据库提供的性能分析器 Apache Bench（ab或者ab2） httperf railsbench 可在http://rubyforge.org/projects/railsbench/下载 我推荐Railsbench，它可以测量Rails处理一个请求的原始性能，关于Railsbench后面的文章会有介绍。 除了基准测试工具，你也可以选择单纯的性能测试工具： Ruby profiler Zen profiler rubyprof Rails profiler script Ruby Performance Validator（商业软件，仅支持windows） 不过事实上，Railsbench已经内置了性能测试工具，所以单独使用这些工具的必要性不大。 工具已经搞定，下面就让我们开始我们的优化之旅吧！ 根据我的经验，Rails性能问题一般集中在以下几个方面： 很慢的helper方法 负责的路由 过多的联合（associations） 过多访问数据库 缓慢的session存取 不过，数据库的性能基本可以不用考虑，因为连接数据库的主要开销事实上在于建立ActiveRecord对象。 这一讲就到这里，下一讲我们将针对以上几个问题给出具体的优化方案。<table class="wumii-related-items" cellspacing="0" cellpadding="2" border="0" width="100%" style="clear: both;">
    
    <tr>
        <td ><b><font size="-1"  style="display: block !important; padding: 20px 0 5px !important;">无觅猜您也喜欢：</font></b></td>
    </tr>
    
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Frails-performance-optimization-guide%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2F12%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">Rails性能优化简明指南</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fupgrade-to-rails-3-beta%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2F12%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">升级到Rails 3 Beta</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2F13%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2F12%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">Rails应用性能优化2</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fusing-rails-reviewer-analytize-rails-performance%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2F12%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">使用rails_reviewer优化Rails数据库查询性能</font>
                    </a>
                </td>
            </tr>
    
    <tr>
        <td  align="right">
            <a style="text-decoration: none !important;" href="http://www.wumii.com/widget/relatedItems.htm" target="_blank" title="无觅相关文章插件">
                <font size="-1" color="#bbbbbb" style="display: block !important; font-family: arial !important; padding: 5px 0 !important; font-size: 12px !important; color: #bbb !important;">无觅</font>
            </a>
        </td>
    </tr>
</table>]]></description>
			<content:encoded><![CDATA[<p>是否觉得你的Rails应用响应速度过于缓慢呢？这是<a href="https://railsexpress.de/blog/files/slides/railsconf2006.pdf" target="_blank">RailsConf2006上的一篇关于Rails应用性能优化的演讲稿</a>，希望能够对你有所帮助。</p>
<p>在优化你的应用之前，我们首先需要明确以下几点：</p>
<ul>
<li>     不先进行性能测试就盲目的优化是非常愚蠢的</li>
<li>     如果你的应用是因为设计不合理而导致性能低下，那么我建议你最好花点时间重构你的代码，而不是进行局部的优化，这只会使问题越来越多。</li>
<li>     在优化之前，最好先为自己树立一个目标，这样可以防止因为过度优化而浪费时间，达到预期的目标后就该适可而止</li>
<li>     没有必要对每一个页面都进行优化，只需要关注那些最经常被访问的页面就可以了，</li>
<li>     在开发期间，进行持续的性能测量，这样有助于你在优化时定位性能瓶颈。</li>
</ul>
<p>在优化完成后，要评估我们优化的质量，我们就需要先确定一组性能参数：</p>
<ul>
<li>     延迟，响应一个请求需要多少时间</li>
<li>     吞吐量，每秒最多可以处理多少个请求</li>
<li>     系统利用率，在大量请求需要处理的时候，你的系统在满负荷运转吗？</li>
<li>     资源开销，在每个请求上所花费的开销</li>
</ul>
<p>确定了要测量的性能参数，我们需要自动化的基准（benchmark）工具来帮我们进行优化前后的性能对比：</p>
<ul>
<li>     Rails日志文件（debug_level &gt;= Logger::DEBUG)</li>
<li>     Rails日志分析工具（需要将日志输出到syslog）</li>
<li>     Rails基准脚本（script/benchmarker）</li>
<li>     数据库提供的性能分析器</li>
<li>     Apache Bench（ab或者ab2）</li>
<li>     httperf</li>
<li>     railsbench
<ul>
<li>       可在<a href="http://rubyforge.org/projects/railsbench/" target="_blank">http://rubyforge.org/projects/railsbench/</a>下载</li>
</ul>
</li>
</ul>
<p>我推荐Railsbench，它可以测量Rails处理一个请求的原始性能，关于Railsbench后面的文章会有介绍。<br />
除了基准测试工具，你也可以选择单纯的性能测试工具：</p>
<ul>
<li>     Ruby profiler</li>
<li>     Zen profiler</li>
<li>     rubyprof</li>
<li>     Rails profiler script</li>
<li>     Ruby Performance Validator（商业软件，仅支持windows）</li>
</ul>
<p>不过事实上，Railsbench已经内置了性能测试工具，所以单独使用这些工具的必要性不大。<br />
工具已经搞定，下面就让我们开始我们的优化之旅吧！</p>
<p>根据我的经验，Rails性能问题一般集中在以下几个方面：</p>
<ul>
<li>     很慢的helper方法</li>
<li>     负责的路由</li>
<li>过多的联合（associations）</li>
<li>     过多访问数据库</li>
<li>     缓慢的session存取</li>
</ul>
<p>不过，数据库的性能基本可以不用考虑，因为连接数据库的主要开销事实上在于建立ActiveRecord对象。</p>
<p>这一讲就到这里，下一讲我们将针对以上几个问题给出具体的优化方案。</p>
<table class="wumii-related-items" cellspacing="0" cellpadding="2" border="0" width="100%" style="clear: both;">
    
    <tr>
        <td ><b><font size="-1"  style="display: block !important; padding: 20px 0 5px !important;">无觅猜您也喜欢：</font></b></td>
    </tr>
    
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Frails-performance-optimization-guide%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2F12%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">Rails性能优化简明指南</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fupgrade-to-rails-3-beta%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2F12%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">升级到Rails 3 Beta</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2F13%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2F12%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">Rails应用性能优化2</font>
                    </a>
                </td>
            </tr>
            <tr>
                <td style="margin: 0 !important; padding: 0 !important; line-height: 20px !important;">
                    <img border="0" src="http://static.wumii.com/images/widget/widget_solidPoint.gif">
                    <a target="_blank" style="text-decoration: none !important;" href="http://app.wumii.com/ext/redirect.htm?url=http%3A%2F%2Fwww.letrails.cn%2Farchives%2Fusing-rails-reviewer-analytize-rails-performance%2F&from=http%3A%2F%2Fwww.letrails.cn%2Farchives%2F12%2F">
                        <font size="-1" color="#333333" style="line-height: 1.65em; font-size: 12px !important;">使用rails_reviewer优化Rails数据库查询性能</font>
                    </a>
                </td>
            </tr>
    
    <tr>
        <td  align="right">
            <a style="text-decoration: none !important;" href="http://www.wumii.com/widget/relatedItems.htm" target="_blank" title="无觅相关文章插件">
                <font size="-1" color="#bbbbbb" style="display: block !important; font-family: arial !important; padding: 5px 0 !important; font-size: 12px !important; color: #bbb !important;">无觅</font>
            </a>
        </td>
    </tr>
</table>]]></content:encoded>
			<wfw:commentRss>http://www.letrails.cn/archives/12/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
	</channel>
</rss>

