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

Optimize #rotate! #11198

Merged

Conversation

HertzDevil
Copy link
Contributor

This PR has a few related optimizations:

  • Ensures that passing n = 0 or a multiple of size in the default Indexable::Mutable implementation skips the loop altogether.
  • Moves the existing optimization in Array#rotate! to Slice, so that any Slice-based container could leverage it. This includes BitArray (only when n and size are both multiples of 8, i.e. the rotation can be done on byte boundaries), and StaticArray.
  • Adds an optimization for BitArrays when rotating 32 or fewer elements in either direction. It uses integer shifts and continues taking O(1) space, so it is very fast compared to the default algorithm. Benchmarks:
    require "benchmark"
    require "bit_array"
    
    SIZES = [0, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 5, 10, 20, 50, 100, 200, 500].sort!
    
    x : BitArray? = nil
    Benchmark.ips do |b|
      SIZES.each do |size|
        {8, 19}.each do |n|
          b.report("new rotate!(#{n})") do
            ba = BitArray.new(size)
            ba.fill { rand > 0.5 }
            100.times { ba.rotate!(n) }
            x = ba
          end
          # ditto for the old `#rotate!`
        end
      end
    end
    rotate

Copy link
Member

@sdogruyol sdogruyol left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚀 Thank you @HertzDevil 🙏

@beta-ziliani beta-ziliani added this to the 1.2.0 milestone Sep 28, 2021
@straight-shoota straight-shoota merged commit c172bd9 into crystal-lang:master Sep 29, 2021
@HertzDevil HertzDevil deleted the perf/indexable-mutable-rotate branch September 30, 2021 02:12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

4 participants