Skip to content

Commit

Permalink
Optimize Range#size for integers
Browse files Browse the repository at this point in the history
  • Loading branch information
asterite committed Jun 12, 2017
1 parent c8ec408 commit 5370faf
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
12 changes: 12 additions & 0 deletions spec/std/range_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -368,6 +368,18 @@ describe "Range" do
end
end

describe "size" do
it "optimizes for int range" do
(5..12).size.should eq(8)
(5...12).size.should eq(7)
(5..4).size.should eq(0)
end

it "works for other types" do
('a'..'c').size.should eq(3)
end
end

it "clones" do
range = [1]..[2]
clone = range.clone
Expand Down
15 changes: 15 additions & 0 deletions src/range.cr
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,21 @@ struct Range(B, E)
end
end

# :nodoc:
def size
b = self.begin
e = self.end

# Optimized implementation for int range
if b.is_a?(Int) && e.is_a?(Int)
e -= 1 if @exclusive
n = e - b + 1
n < 0 ? 0 : n
else
super
end
end

private class ItemIterator(B, E)
include Iterator(B)

Expand Down

0 comments on commit 5370faf

Please sign in to comment.