Last active
October 1, 2019 12:01
-
-
Save goromlagche/d0305f1bb72ea1d01372fce3c91553d1 to your computer and use it in GitHub Desktop.
its better to use `date + Time.zone.utc_offset` rather than `Time.zone.parse(date.to_s)` if you are worried about performance, and if you only need the value, not the whole object.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| require 'benchmark/ips' | |
| require 'active_support/all' | |
| LOOP_FOR = 100_000 | |
| Time.zone = 'Hawaii' | |
| DATE = Time.current.getutc | |
| # a certain custom time format | |
| Time::DATE_FORMATS[:local_db] = | |
| ->(time) { time.strftime(Time::DATE_FORMATS[:db]) } | |
| def faster | |
| offset = Time.zone.utc_offset | |
| LOOP_FOR.times do | |
| (DATE + offset).to_s(:local_db) | |
| end | |
| end | |
| def fast | |
| LOOP_FOR.times do | |
| DATE.in_time_zone.to_s(:local_db) | |
| end | |
| end | |
| def slow | |
| LOOP_FOR.times do | |
| Time.zone.parse(DATE.to_s).to_s(:local_db) | |
| end | |
| end | |
| Benchmark.ips do |x| | |
| x.report('use and cache offset') { faster } | |
| x.report('use zone') { fast } | |
| x.report('parse with zone') { slow } | |
| x.compare! | |
| end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Warming up -------------------------------------- | |
| use and cache offset 1.000 i/100ms | |
| use zone 1.000 i/100ms | |
| parse with zone 1.000 i/100ms | |
| Calculating ------------------------------------- | |
| use and cache offset 3.053 (± 0.0%) i/s - 16.000 in 5.288739s | |
| use zone 0.588 (± 0.0%) i/s - 3.000 in 5.280270s | |
| parse with zone 0.151 (± 0.0%) i/s - 1.000 in 6.605711s | |
| Comparison: | |
| use and cache offset: 3.1 i/s | |
| use zone: 0.6 i/s - 5.19x slower | |
| parse with zone: 0.2 i/s - 20.17x slower |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment