下面是从日志摘出来的:
Rendered api/list.json.jbuilder (115.6ms)
Completed 200 OK in 408ms (Views: 187.9ms | ActiveRecord: 4.3ms)
业务逻辑:极为简单的逻辑,返回一个帖子的 5 条回复 通过 Jbuilder 返回 5 条回复的 Json 数据给前端。
结果发现 views 的时间远远大于 db 的时间,这种情况该如何优化?
jbuilder 的代码如下:
json.array!(@comments) do |comment|
json.extract! comment, :id, :content, :user_id, :topic_id, :reply_count
#json.url api_comment_url(comment, format: :json)
end
超过 1 行代码,超过 2 ms,剁 JJ
@comments.to_json(only: [ :id, :content, :user_id, :topic_id, :reply_count ], methods: [ :url ])
defaulf json backend is too slow
from jbuilder github readme
Faster JSON backends
Jbuilder uses MultiJson, which by default will use the JSON gem. That gem is currently tangled with ActiveSupport's all-Ruby #to_json implementation, which is slow (work is being done to correct this for a future version of Rails). For faster Jbuilder rendering, you can specify something like the Yajl JSON generator instead. You'll need to include the>yajl-ruby gem in your Gemfile and then set the following configuration for MultiJson:
require 'multi_json'
MultiJson.use :yajl