我有1.6GB的xml文件,當我使用SAX解析機它,它似乎並不爲串流或進食以塊的文件 - 而是出現要將整個文件加載到內存中(或者可能存在內存泄漏?),因爲我的紅寶石進程爬上了2.5gb的內存。我不知道它會停止增長,因爲我內存不足。解析與SaxMachine大文件似乎整個文件被加載到內存中
在一個更小的文件(50MB),它似乎也加載整個文件。我的任務遍歷xml文件中的記錄並將每條記錄保存到數據庫中。大約需要30秒的「怠速」,然後數據庫查詢突然開始執行。
我認爲SAX是應該讓你與這樣的大文件而不用在內存中加載了整個事情。
有什麼我可以忽略的嗎?
非常感謝
更新添加代碼示例
class FeedImporter
class FeedListing
include ::SAXMachine
element :id
element :title
element :description
element :url
def to_hash
{}.tap do |hash|
self.class.column_names.each do |key|
hash[key] = send(key)
end
end
end
end
class Feed
include ::SAXMachine
elements :listing, :as => :listings, :class => FeedListing
end
def perform
open('~/feeds/large_feed.xml') do |file|
# I think that SAXMachine is trying to load All of the listing elements into this one ruby object.
puts 'Parsing'
feed = Feed.parse(file)
# We are now iterating over each of the listing elements, but they have been "parsed" from the feed already.
puts 'Importing'
feed.listings.each do |listing|
Listing.import(listing.to_hash)
end
end
end
end
正如你所看到的,我不在乎在飼料中<listings>
元素。我只想要每個<listing>
元素的屬性。
輸出看起來是這樣的:
Parsing
... wait forever
Importing (actually, I don't ever see this on the big file (1.6gb) because too much memory is used :(
簡單回答你的問題:是的,有你忽視的東西。不幸的是你沒有告訴我們它是什麼。沒有人可以在他們看不到的代碼中發現內存泄漏。 – 2012-02-08 22:02:04
@MichaelKay我已經添加了一個示例。謝謝 – jakeonrails 2012-02-09 00:49:43