2013-07-02 21 views
2

我在軌道上的Web應用程序存儲在XML字符串中的一些模型對象的參數,所以無論何時我需要關於特定對象的一些信息,我必須解析它的XML字符串。 XML的長度很少超過100行。但由於我的願望優化我不知道我是否可以將分析的XML作爲Nokogiri的對象存儲在數據庫中。這是個好主意嗎?將nokogiri(或任何內部)對象保存到數據庫是一個好主意嗎?

+2

爲什麼不返工數據庫模式,這樣你不存儲XML呢?我懷疑Nokogiri文檔是以任何理智的方式序列化的,除非將它們轉換回XML。 –

+1

我討厭想到這會對代碼運行時造成的影響。如果你試圖節省內存,你是這樣做的,以犧牲速度爲代價。相反,購買更多的RAM並將其保存在內存中。 –

回答

2

儘管可能有例外情況,但一般來說,您應該避免將marshalled objects直接存儲在您的數據庫中,除非您有一個很好的理由。在引入nokogiri的情況下,@ MU-是太短暫mentioned,引入nokogiri和元帥不玩好起來:

doc = Nokogiri::HTML(some_html)  
Marshal.dump doc 
# => TypeError: no _dump_data is defined for class Nokogiri::HTML::Document 

這就是說,Marshal#loadMarshal#dump是核心Ruby庫的一部分,是相當玩的樂趣。除了with the docs,這裏是展示一個快速的代碼示例元帥是如何工作的,包括一個非常基本的基準比較Marshal.loadClass.new

require 'benchmark' 

data_string = <<-DATA 
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod 
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo 
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse 
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non 
proident, sunt in culpa qui officia deserunt mollit anim id est laborum. 
DATA 

class Example 
    attr_reader :data 

    def initialize(data) 
    @data = data 
    end 
end 

example = Example.new(data_string) 

dumped = Marshal.dump example 
loaded = Marshal.load dumped 

puts "String Bytesize: #{data_string.bytesize} vs. Dump Bytesize: #{dumped.bytesize}" 
puts "Marshalled object is larger by #{dumped.bytesize - data_string.bytesize} bytes" 

Benchmark.bmbm do |x| 
    x.report("Marshal.load: ") { Marshal.load(dumped).data } 
    x.report(" Example.new: ") { Example.new(data_string).data } 
end 
+0

謝謝大家!你的幫助是無價的:特別是我的僱主) –

相關問題