From 9128ba5cd496eed89e14f92f7b3fdbed1bdf5750 Mon Sep 17 00:00:00 2001 From: Andrew White Date: Sun, 2 Oct 2016 17:15:44 +0100 Subject: [PATCH] Cache to_time to improve performance when comparing In #25880 we tried to cache localtime to fix the performance regression but that proved to be difficult due to the fact that localtime/getlocal can take a utc_offset argument. We tried caching based on the argument but since the argument can be nil sometimes that meant that if the TZ environment variable changed then the cached value for nil became invalid. By moving the caching to DateAndTime#compatibility we don't have to worry about arguments since it doesn't take any. There is a possible edge condition where preserve_timezone is set to false and the system timezone changes then it could result in a cached value being incorrect but the only way to fix this would be to remove all caching and live with the performance issue. --- .../active_support/core_ext/date_and_time/compatibility.rb | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/activesupport/lib/active_support/core_ext/date_and_time/compatibility.rb b/activesupport/lib/active_support/core_ext/date_and_time/compatibility.rb index 3f4e236ab7..db95ae0db5 100644 --- a/activesupport/lib/active_support/core_ext/date_and_time/compatibility.rb +++ b/activesupport/lib/active_support/core_ext/date_and_time/compatibility.rb @@ -12,7 +12,11 @@ module Compatibility mattr_accessor(:preserve_timezone, instance_writer: false) { false } def to_time - preserve_timezone ? getlocal(utc_offset) : getlocal + if preserve_timezone + @_to_time_with_instance_offset ||= getlocal(utc_offset) + else + @_to_time_with_system_offset ||= getlocal + end end end end -- GitLab