新手问题 rails 的 json.jbuilder 渲染很慢,如何优化?

dizhu · 2014年02月28日 · 最后由 pynix 回复于 2014年03月01日 · 7820 次阅读

下面是从日志摘出来的:

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

不用它...

有代码吗?

jbuilder 很快的,感觉是你的代码有问题

#2 楼 @Rei 代码我更新到帖子上去了。

#1 楼 @zgm 有更好的方式吗?

我自己构造 hash 然后 render json: hash. 之前内容多了以后我也发现了 jbuilder 的性能不行。

#6 楼 @zgm 你的意思是压根就不用 jbuilder 模板渲?

#7 楼 @dizhu 我是这个意思。你可以做个试验看看差多少。

#6 楼 @zgm 内容多大概是有多大的 json 数据,10k?100k?渲染时间大概是多少?想了解一下 jbuilder 的使用上限

#9 楼 @aptx4869 总共五条数据

用了 oj 么?

#11 楼 @hbin oj 是什么?

jbuilder 支持缓存,可以缓存一些试试看

超过 1 行代码,超过 2 ms,剁 JJ

@comments.to_json(only: [ :id, :content, :user_id, :topic_id, :reply_count ], methods: [ :url ])

没看出代码问题,jbuilder 按理说不会这么慢,替换别的模板试试,例如 json.erb。

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
需要 登录 后方可回复, 如果你还没有账号请 注册新账号