Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add new Performance/StringIdentifierArgument cop #276

Commits on Dec 7, 2021

  1. Add new Performance/StringIdentifierArgument cop

    This PR adds new `Performance/StringIdentifierArgument` cop.
    
    This cop identifies places where string identifier argument can be replaced
    by symbol identifier argument.
    It prevents the redundancy of the internal string-to-symbol conversion.
    
    This cop targets methods that take identifier (e.g. method name) argument
    and the following examples are parts of it.
    
    ```ruby
    # bad
    send('do_something')
    attr_accessor 'do_something'
    instance_variable_get('@ivar')
    
    # good
    send(:do_something)
    attr_accessor :do_something
    instance_variable_get(:@ivar)
    ```
    
    The `send` method is a representative and other similar methods are
    similar benchmarks. The following is an example benchmark.
    
    ```ruby
    % cat symbol.rb
    puts `ruby -v`
    
    require 'benchmark/ips'
    
    def foo
    end
    
    Benchmark.ips do |x|
      x.report('symbol arg') { send(:foo) }
      x.report('string arg') { send('foo') }
    
      x.compare!
    end
    ```
    
    ```console
    % ruby symbol.rb
    ruby 3.1.0dev (2021-12-05T10:23:42Z master 19f037e452) [x86_64-darwin19]
    Warming up --------------------------------------
              symbol arg     1.025M i/100ms
              string arg   590.038k i/100ms
    Calculating -------------------------------------
              symbol arg     10.665M (± 1.5%) i/s -     53.318M in 5.000551s
    
              string arg      5.895M (± 1.0%) i/s -     29.502M in 5.004999s
    
    Comparison:
              symbol arg: 10665035.8 i/s
              string arg:  5895132.3 i/s - 1.81x  (± 0.00) slower
    ```
    
    I learned about this performance difference from the book "Polished Ruby Programming".
    koic committed Dec 7, 2021
    Configuration menu
    Copy the full SHA
    9a52662 View commit details
    Browse the repository at this point in the history