jbuilder会构建一个包含您数据的大哈希值,然后使用ActiveSupport::JSON
将其转换为json格式。如以下微基准测试所示,有更快速的json发射器(请确保已安装multijson和yajl-ruby宝石)。
require 'benchmark'
require 'active_support'
require 'multi_json'
sample = {menu: {
header: "SVG Viewer",
items: [
{id: "Open"},
{id: "OpenNew", label: "Open New"},
nil,
{id: "ZoomIn", label: "Zoom In"},
{id: "ZoomOut", label: "Zoom Out"},
{id: "OriginalView", label: "Original View"},
nil,
{id: "Quality"},
{id: "Pause"},
{id: "Mute"},
nil,
{id: "Find", label: "Find..."},
{id: "FindAgain", label: "Find Again"},
{id: "Copy"},
{id: "CopyAgain", label: "Copy Again"},
{id: "CopySVG", label: "Copy SVG"},
{id: "ViewSVG", label: "View SVG"},
{id: "ViewSource", label: "View Source"},
{id: "SaveAs", label: "Save As"},
nil,
{id: "Help"},
{id: "About", label: "About Adobe CVG Viewer..."}
]
}}
MultiJson.engine = :yajl
Benchmark.bmbm(5) do |x|
x.report 'activesupport' do
1000.times {ActiveSupport::JSON.encode(sample)}
end
x.report 'yajl' do
1000.times {MultiJson.encode(sample)}
end
end
在我的电脑上,这会产生以下结果
user system total real
activesupport 1.050000 0.010000 1.060000 ( 1.068426)
yajl 0.020000 0.000000 0.020000 ( 0.021169)
将示例对象编码1000次,Active Support耗时略超过1秒,而MultiJson(使用yajl引擎)只需21毫秒。
JBuilder硬编码使用ActiveSupport :: JSON,但MultiJSON(一个可以在不同json库之间切换的gem)是一个微不足道的插件,并且已经是ActiveSupport的依赖项 - 请参见我的jbuilder的fork。我已经发起了一个拉取请求,但在此之前,您可以尝试使用这个分支(或创建自己的分支-它只需要一行代码更改)。