Sha256: dff08e79dcc8bb7118504cb564aa1ccf33d2862f534425bb39248efef61034cf

Contents?: true

Size: 1.53 KB

Versions: 26

Compression:

Stored size: 1.53 KB

Contents

require 'benchmark'

class Selector


  def initialize(key)
    @key = key
  end

  def selector_if
    if @key == :success
      'alert-success'
    elsif @key == :error
      'alert-danger'
    elsif @key == :warn
      'alert-warning'
    elsif @key == :info
      'alert-info'
    end
  end

  def selector_case
    case @key
      when :success then 'alert-success'
      when :error   then 'alert-danger'
      when :warn    then 'alert-warning'
      when :info    then 'alert-info'
    end
  end

  ALERT_TYPES = { success: 'alert-success',
                  error:   'alert-danger',
                  notice:  'alert-info',
                  warn:    'alert-warning' }

  def selector_hash_cached
    ALERT_TYPES[@key]
  end

  def selector_hash
    { success: 'alert-success',
      error:   'alert-danger',
      notice:  'alert-info',
      warn:    'alert-warning' }[@key]
  end
end

Benchmark.bm(25) do |x|
  x.report("if") { 
    1.times do 
      selector = Selector.new([:success, :error, :notice, :warn].sample)
      selector.selector_if
    end
  }

  x.report("case") { 
    1.times do 
      selector = Selector.new([:success, :error, :notice, :warn].sample)
      selector.selector_case
    end
  }
 
  x.report("hash_select_cached") { 
    1.times do 
      selector = Selector.new([:success, :error, :notice, :warn].sample)
      selector.selector_hash_cached
    end
  }

  x.report("hash_select") { 
    1.times do 
      selector = Selector.new([:success, :error, :notice, :warn].sample)
      selector.selector_hash
    end
  }
end

Version data entries

26 entries across 26 versions & 1 rubygems

Version Path
writefully-0.4.5 spec/dummy/content/codemy-net/posts/1-hash-selector-pattern/benchmark/selector.rb
writefully-0.4.4 spec/dummy/content/codemy-net/posts/1-hash-selector-pattern/benchmark/selector.rb
writefully-0.4.2 spec/dummy/content/codemy-net/posts/1-hash-selector-pattern/benchmark/selector.rb
writefully-0.4.1 spec/dummy/content/codemy-net/posts/1-hash-selector-pattern/benchmark/selector.rb
writefully-0.4.0 spec/dummy/content/codemy-net/posts/1-hash-selector-pattern/benchmark/selector.rb
writefully-0.3.6 spec/dummy/content/codemy-net/posts/1-hash-selector-pattern/benchmark/selector.rb