2009-08-07 32 views
0

我想渲染一個大的(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文檔 - 它的工作原理實際上是兩倍的緩慢!

任何想法如何改善這一點,或以其他方式確定瓶頸?

+0

「to_plist」方法有什麼作用? – 2009-08-07 16:40:56

+0

to_plist方法來自plist gem--它會自動將給定散列轉換爲字符串形式的plist(即q中顯示的XML文檔格式) – frankodwyer 2009-08-07 16:45:57

回答

1

不知道你是否可以做很多事情來改善這種情況,而不會在plist寶石本身中盜用。看看存儲庫中的源代碼「svn checkout http://plist.rubyforge.org/svn/」和here它看起來像gem獨立生成XML,而不是使用XML庫(如LibXML,Nokogiri或builder)。

我不確定使用這些庫中的一個庫會在爲您生成XML(它們肯定是解析速度更快)時會產生多大的差異,但它似乎是尋找優化機會的第一個合理位置。

相關問題