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

[stdlib] fix zero based range performance #3932

Open
wants to merge 2 commits into
base: nightly
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 9 additions & 9 deletions stdlib/src/builtin/range.mojo
Original file line number Diff line number Diff line change
Expand Up @@ -46,41 +46,41 @@ fn _sign(x: Int) -> Int:

@register_passable("trivial")
struct _ZeroStartingRange(Sized, ReversibleRange, _IntIterable):
var curr: Int
var start: Int
var end: Int

@always_inline
@implicit
fn __init__(out self, end: Int):
self.curr = max(0, end)
self.end = self.curr
self.start = 0
self.end = end

@always_inline
fn __iter__(self) -> Self:
return self

@always_inline
fn __next__(mut self) -> Int:
var curr = self.curr
self.curr -= 1
return self.end - curr
var start = self.start
self.start += 1
return start

@always_inline
fn __has_next__(self) -> Bool:
return self.__len__() > 0
Copy link
Contributor

Choose a reason for hiding this comment

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

Another place where we can add a micro-optimization :D

Suggested change
return self.__len__() > 0
return self.end > self.start


@always_inline
fn __len__(self) -> Int:
return self.curr
return max(0, self.end - self.start)
Copy link
Contributor

Choose a reason for hiding this comment

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

I think we could make this branchless. No idea how often this gets called or if the optimization would have a positive effect. Would you be willing to measure the diff using something like

return (self.end - self.start) & -int(self.end > self.start)

Copy link
Author

Choose a reason for hiding this comment

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

Totally! I'll post some numbers when I have them


@always_inline
fn __getitem__(self, idx: Int) -> Int:
debug_assert(idx < self.__len__(), "index out of range")
return index(idx)
return self.start + index(idx)

@always_inline
fn __reversed__(self) -> _StridedRange:
return range(self.end - 1, -1, -1)
return range(self.end - 1, self.start - 1, -1)


@value
Expand Down
Loading