我的 Rails 上的 Web 应用程序将一些模型对象的参数存储在 XML 字符串中,因此每当我需要有关特定对象的一些信息时,我都必须解析其 XML 字符串。 XML 的长度很少超过 100 行。但由于我想要优化,我想知道是否可以将解析后的 XML 作为 Nokogiri 的对象存储在数据库中。这是个好主意吗?
最佳答案
虽然可能有异常(exception),但一般来说,您应该避免存储 marshalled objects直接在您的数据库中,除非您有非常充分的理由。就 Nokogiri 而言,如@mu-is-too-short mentioned ,Nokogiri 和 Marshal 在一起玩得不好:
doc = Nokogiri::HTML(some_html)
Marshal.dump doc
# => TypeError: no _dump_data is defined for class Nokogiri::HTML::Document
也就是说,Marshal#load和 Marshal#dump是核心 Ruby 库的一部分,使用起来非常有趣。沿with the docs ,这里是一个快速代码示例,展示了 Marshal 的工作原理,包括一个非常基本的基准测试,将 Marshal.load
与 Class.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
关于ruby-on-rails - 将 nokogiri (或任何内部)对象保存到数据库是个好主意吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17417682/