dry-rb / dry-inflector

Inflector for Ruby
https://dry-rb.org/gems/dry-inflector
MIT License
95 stars 15 forks source link

Perf: Speed-up `humanize` #18

Closed splattael closed 6 years ago

splattael commented 6 years ago

Hi,

first of all: Thank you for dry-inflector 💚 🎉

I found a small performance improvement in Dry::Inflector#humanize: Prefer chomp!("XXX") over gsub!(/XXX\z/, "").

Please find the benchmark and the results below :neckbeard:

Benchmark

# frozen_string_literal: true

require "benchmark/ips"
require "dry/inflector"

inputs = ["", "dry_inflector", "author_id"]

inflector = Dry::Inflector.new

class Dry::Inflector
  def humanize2(input)
    input = input.to_s
    result = inflections.humans.apply_to(input)
    result.chomp!("_id") # <=--- WAS `result.gsub!(/_id\z/, "")`
    result.tr!("_", " ")
    result.capitalize!
    result
  end
end

inputs.each do |input|
  puts "INPUT: #{input.inspect}"

  Benchmark.ips do |x|
    x.report("old") { inflector.humanize(input) }
    x.report("new") { inflector.humanize2(input) }

    x.compare!
  end

  puts
end

Results

INPUT: ""
Warming up --------------------------------------
                 old    78.958k i/100ms
                 new   100.336k i/100ms
Calculating -------------------------------------
                 old    959.997k (± 6.4%) i/s -      4.816M in   5.041162s
                 new      1.302M (± 6.1%) i/s -      6.522M in   5.031563s

Comparison:
                 new:  1302044.5 i/s
                 old:   959996.6 i/s - 1.36x  slower

INPUT: "dry_inflector"
Warming up --------------------------------------
                 old    57.072k i/100ms
                 new    66.649k i/100ms
Calculating -------------------------------------
                 old    653.975k (± 5.1%) i/s -      3.310M in   5.076730s
                 new    783.289k (± 5.3%) i/s -      3.932M in   5.036613s

Comparison:
                 new:   783289.3 i/s
                 old:   653974.8 i/s - 1.20x  slower

INPUT: "author_id"
Warming up --------------------------------------
                 old    34.459k i/100ms
                 new    69.931k i/100ms
Calculating -------------------------------------
                 old    373.581k (± 6.8%) i/s -      1.861M in   5.007815s
                 new    834.177k (± 5.7%) i/s -      4.196M in   5.049382s

Comparison:
                 new:   834176.6 i/s
                 old:   373581.3 i/s - 2.23x  slower

Feedback is welcome!

Kind regards, Peter

Ptico commented 6 years ago

Very clever, thanks!