Skip to content

Commit

Permalink
[PERF] Speed up integer type casting from DB
Browse files Browse the repository at this point in the history
We don't have the check the range when the value is coming from the DB, so
override type_cast_from_database to short-circuit the extra work.

type_cast_from_database (small)  3437507.5 (±29.2%) i/s -   14223135 in   4.996973s
type_cast_from_database (large)  3158588.7 (±28.3%) i/s -   13265628 in   4.992121s
type_cast (small)                 481984.8 (±14.2%) i/s -    2352012 in   5.005694s
type_cast (large)                 477331.8 (±14.2%) i/s -    2332824 in   5.012365s

Comparison:
type_cast_from_database (small):  3437507.5 i/s
type_cast_from_database (large):  3158588.7 i/s - 1.09x slower
type_cast (small):                 481984.8 i/s - 7.13x slower
type_cast (large):                 477331.8 i/s - 7.20x slower

The difference is huge but the absolute gain is quite small. That being said
this is a hotspot and it showed up on the radar when benchmarking discourse.
  • Loading branch information
chancancode committed Nov 18, 2014
1 parent eb26f24 commit 6f7910a
Showing 1 changed file with 3 additions and 1 deletion.
4 changes: 3 additions & 1 deletion activerecord/lib/active_record/type/integer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@ def type
:integer
end

alias type_cast_for_database type_cast
def type_cast_from_database(value)
value.to_i unless value.nil?
end

protected

Expand Down

0 comments on commit 6f7910a

Please sign in to comment.