我想渲染一個大的(ish)對象數組作爲Ruby on Rails中的plist。該集合目前最多包含200個對象,每個對象本質上都是一個記錄(鍵/值字典)。整體結果格式爲plist(Apple使用),但邏輯上與任何XML文檔沒有多大區別。在ruby/rails中渲染大型XML集合的有效方法是什麼?
我碰到的問題是渲染數組花費了大約200秒的時間,這對我來說似乎非常慢。我目前使用這樣的代碼:
def plistify(collection)
resultarray=Array.new()
collection.each do |entry|
hash= entry.attributes
hash["credits"]= entry.credits
hash["ratingcount"]= entry.ratings.count
hash["entryrating"]= entry.detail_rating
hash["entryratingcount"]= entry.entryratingcount
resultarray << hash
end
{'entries'=>resultarray}.to_plist
end
然後被髮送到客戶端使用:
format.text {render :text => plistify(@entries)}
,輸出結果是這樣的:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>entries</key>
<array> <-- corresponds to resultarray above
<dict> <-- corresponds to a single entry's attributes above. one of these per entry.
<key>cached_review_id</key>
<integer>190</integer>
<key>cached_tag_list</key>
<string>pub restaurant food waitress</string>
<key>created_at</key>
<date>2009-05-31T13:47:10Z</date>
...about 20 key/values...
等幾乎所有開銷在ruby'plistify'代碼中 - 相比之下,數據庫開銷很小。
假設開銷可能來自創建大量臨時ruby對象,我試圖用視圖替換所有這些,並在視圖中使用Builder來創建相同的XML文檔 - 它的工作原理實際上是兩倍的緩慢!
任何想法如何改善這一點,或以其他方式確定瓶頸?
「to_plist」方法有什麼作用? – 2009-08-07 16:40:56
to_plist方法來自plist gem--它會自動將給定散列轉換爲字符串形式的plist(即q中顯示的XML文檔格式) – frankodwyer 2009-08-07 16:45:57