Skip to content

Instantly share code, notes, and snippets.

@hooopo
Created August 24, 2012 08:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hooopo/3447628 to your computer and use it in GitHub Desktop.
Save hooopo/3447628 to your computer and use it in GitHub Desktop.
AR serialize or deserialize
require 'benchmark'
def serialize(record)
[record.class.name, record.instance_variable_get(:@attributes)]
end
def deserialize(serialized)
record = serialized[0].constantize.allocate
record.init_with('attributes' => serialized[1])
record
end
# 通过Rails.cache自带的方法来实现序列化/反序列化AR对象
def native_deserialize(record)
record.clear_association_cache
Rails.cache.write :native, record
Rails.cache.read :native
end
# 通过数组存储类名,和属性来实现序列化/反序列化AR对象
def array_deserialize(record)
Rails.cache.write :array, serialize(record)
deserialize(Rails.cache.read :array)
end
def run_bm(user)
Benchmark.bm(20) do |x|
x.report("array:") {5000.times{array_deserialize(user) }}
x.report("native:") {5000.times{native_deserialize(user) }}
end
end
user = User.first
run_bm(user)
-------------------------------------------------------------------
user system total real
array: 2.760000 0.270000 3.030000 ( 3.050988)
native: 3.580000 0.250000 3.830000 ( 3.834514)
-------------------------------------------------------------------
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment