Permalink
Browse files

performance improvements

- memoize example => emitters (10x improvement)
- build composite format with .each instead of
  .map.join (20% improvement)
  • Loading branch information...
1 parent e79ff7b commit 62d78c58fdc2dab2d8d7de09c95e6e32acc383dc @jeremyw committed Dec 12, 2012
Showing with 17 additions and 7 deletions.
  1. +6 −3 lib/stamp.rb
  2. +5 −3 lib/stamp/emitters/composite.rb
  3. +6 −1 lib/stamp/translator.rb
View
@@ -16,13 +16,16 @@ module Stamp
# Formats a date/time using a human-friendly example as a template.
#
- # @param [String] example a human-friendly date/time example
+ # @param [String] example a human-friendly date/time example
+ # @param [Hash] options
+ # @option options [Boolean] :memoize (true)
+ #
# @return [String] the formatted date or time
#
# @example
# Date.new(2012, 12, 21).stamp("Jan 1, 1999") #=> "Dec 21, 2012"
- def stamp(example)
- Translator.new.translate(example).format(self)
+ def stamp(example, options=nil)
+ Translator.new.translate(example, options).format(self)
end
alias :stamp_like :stamp
alias :format_like :stamp
@@ -3,14 +3,16 @@ module Emitters
class Composite
include Enumerable
- EMPTY_STRING = ''
-
def initialize
@emitters = []
end
def format(target)
- @emitters.map { |e| e.format(target) }.join(EMPTY_STRING)
+ # NOTE using #each to build string because benchmarking shows
+ # that it's ~20% faster than .map.join('')
+ result = ''
+ @emitters.each { |e| result << e.format(target).to_s }
+ result
@kbrock
kbrock Dec 12, 2012 Contributor

A performance tweak that had always been on my mind was passing in the result to format for all formatters

@emitters.each { |e| e.format(result, target) }
end
def <<(emitter)
@@ -61,7 +61,12 @@ class Translator
:min => Emitters::TwoDigit.new(:sec)
}
- def translate(example)
+ def translate(example, options=nil)
+ unless options && options[:memoize] == false
+ @@translations ||= {}
+ return @@translations[example] ||= translate(example, :memoize => false)
+ end
+
# extract any substrings that look like times, like "23:59" or "8:37 am"
before, time_example, after = example.partition(TIME_REGEXP)

0 comments on commit 62d78c5

Please sign in to comment.