2
如何讓ActiveSupport::TimeWithZone
更快地構建或懶惰?使Rails中的TimeWithZone對象變懶惰
我一直在分析我的Rails應用程序,我發現cpu時間的三分之一用於構建這些TimeWithZone
對象。我憑我的智慧結束了這一切。看起來簡單的時間對象如何構造起來可能如此昂貴?
這裏是每個請求運行bazillion倍的代碼:
def deserialize_from_cache(json)
attributes = ActiveSupport::JSON.decode(json)
attributes.keys.to_a.each do |k|
v = attributes[k]
if v.is_a? Array and v.length == 2 and v[0] == 'Time'
attributes[k] = Time.at(v[1]).in_time_zone # This is the expensive code
end
end
self.allocate.init_with('attributes' => attributes)
end
我基準普通老式Time
對象結構,並發現它是一個數量級比TimeWithZone
施工速度更快:
puts Benchmark.measure { 200000.times { Time.at(1330367843) } }
0.070000 0.000000 0.070000 ( 0.068956)
puts Benchmark.measure { 200000.times { Time.at(1330367843).in_time_zone } }
0.720000 0.000000 0.720000 ( 0.715802)
有沒有什麼,我可以做的,以編程方式取代所有模型的日期時間屬性與懶惰TimeWithZone
對象是普通的舊(和便宜的)Time
對象,直到他們在哪個時間被使用,變成TimeWithZone
對象?這遠遠超出了我的Ruby能力。
生產模式 – guidoism 2012-04-06 03:10:59
您的基準測試在我的筆記本電腦上給出了相當不同的結果(Thinkpad Ubuntu 11.10 Ruby 1.9.3 p125,Rails 3.2.3)。我幾乎在同一時間看到#at方法和#in_time_zone。您的代碼的結果:Time.at:0.060000 0.000000 0.060000(0.054021); Time.at.in_time_zone:0.120000 0.000000 0.120000(0.115737) – joelparkerhenderson 2012-04-06 06:09:32