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

Cop idea: prefer << over push #431

Open
amomchilov opened this issue Jan 10, 2024 · 0 comments · May be fixed by #433
Open

Cop idea: prefer << over push #431

amomchilov opened this issue Jan 10, 2024 · 0 comments · May be fixed by #433

Comments

@amomchilov
Copy link

amomchilov commented Jan 10, 2024

a << i is faster than a.push(e). I suspect it's because #push takes *args, and the overhead from that is relatively slower than <<, which takes a single arg.

$ ruby --version
ruby 3.3.0 (2023-12-25 revision 5124f9ac75) [arm64-darwin23]

Warming up --------------------------------------
                push     2.673M i/100ms
                  <<     3.180M i/100ms
Calculating -------------------------------------
                push     26.901M (± 0.7%) i/s -    136.334M in   5.068171s
                  <<     32.351M (± 0.8%) i/s -    162.187M in   5.013725s

Comparison:
                  <<: 32350784.7 i/s
                push: 26901465.1 i/s - 1.20x  slower
benchmark.rb
require "benchmark/ips"

a = []
    
Benchmark.ips do |x|
  x.report("push") do |times|
    i = 0
    a.clear
    while (i += 1) < times
      a.push(i)
    end
  end
  
  x.report("<<") do |times|
    i = 0
    a.clear
    while (i += 1) < times
      a << i
    end
  end
  
  x.compare!
end
amomchilov added a commit to amomchilov/rubocop-performance that referenced this issue Jan 12, 2024
@amomchilov amomchilov linked a pull request Jan 12, 2024 that will close this issue
8 tasks
amomchilov added a commit to amomchilov/rubocop-performance that referenced this issue Jan 12, 2024
amomchilov added a commit to amomchilov/rubocop-performance that referenced this issue Jan 12, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant