Skip to content

Instantly share code, notes, and snippets.

@rafaelfranca
Last active February 3, 2021 00:09
Show Gist options
  • Save rafaelfranca/0f71c00613f924fcbcdb14b95e6f7661 to your computer and use it in GitHub Desktop.
Save rafaelfranca/0f71c00613f924fcbcdb14b95e6f7661 to your computer and use it in GitHub Desktop.
# frozen_string_literal: true
require "bundler/setup"
require "active_model"
require "benchmark/ips"
class NewTime < ActiveModel::Type::Time
private
def cast_value(value)
return apply_seconds_precision(value) unless value.is_a?(::String)
return if value.empty?
dummy_time_value = value.sub(/\A\d{4}-\d\d-\d\d(?:T|\s)|/, "2000-01-01 ")
fast_string_to_time(dummy_time_value) || begin
time_hash = ::Date._parse(dummy_time_value)
return if time_hash[:hour].nil?
new_time(*time_hash.values_at(:year, :mon, :mday, :hour, :min, :sec, :sec_fraction, :offset))
end
end
end
type = ActiveModel::Type::Time.new
new_type = NewTime.new
SCENARIOS = {
"Incomplete" => "06:07:08+09:00",
"ISO" => "2015-06-13T19:45:54+03:00",
"Hash" => { 4 => 16, 5 => 45, 6 => 54 }
}
SCENARIOS.each_pair do |name, value|
puts
puts " #{name} ".center(80, "=")
puts
Benchmark.ips do |x|
x.report("old") { type.cast(value) }
x.report("new") { new_type.cast(value) }
x.compare!
end
end
================================== Incomplete ==================================
Warming up --------------------------------------
old 21.970k i/100ms
new 20.542k i/100ms
Calculating -------------------------------------
old 211.402k (± 2.7%) i/s - 1.077M in 5.096092s
new 207.805k (± 2.4%) i/s - 1.048M in 5.044402s
Comparison:
old: 211401.7 i/s
new: 207805.1 i/s - same-ish: difference falls within error
===================================== ISO ======================================
Warming up --------------------------------------
old 5.523k i/100ms
new 20.959k i/100ms
Calculating -------------------------------------
old 56.738k (± 3.2%) i/s - 287.196k in 5.067285s
new 205.978k (± 3.8%) i/s - 1.048M in 5.094470s
Comparison:
new: 205978.5 i/s
old: 56737.6 i/s - 3.63x (± 0.00) slower
===================================== Hash =====================================
Warming up --------------------------------------
old 20.880k i/100ms
new 19.386k i/100ms
Calculating -------------------------------------
old 202.984k (± 2.9%) i/s - 1.023M in 5.045013s
new 203.073k (± 2.2%) i/s - 1.027M in 5.061994s
Comparison:
new: 203073.4 i/s
old: 202983.6 i/s - same-ish: difference falls within error
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment