Skip to content

Commit

Permalink
Make .head(N)/.tail(N) faster on native arrays
Browse files Browse the repository at this point in the history
- tail 18x as fast
- head 3.5x as fast

Note that these will now return a native array of the same type,
rather than a Seq.
  • Loading branch information
lizmat committed May 21, 2022
1 parent 7a25fc9 commit 3c47f1d
Showing 1 changed file with 13 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/core.c/native_array.pm6
Expand Up @@ -36,6 +36,19 @@ my class array does Iterable does Positional {
multi method unshift(array:D: **@values) { self.unshift(@values) }
multi method prepend(array:D: *@values) { self.unshift(@values) }

multi method head(array:D: Int:D $n) {
my int $end = $n - 1;
nqp::isgt_i($end,nqp::elems(self))
?? nqp::clone(self)
!! nqp::slice(self,0,$end)
}
multi method tail(array:D: Int:D $n) {
my int $start = nqp::elems(self) - $n;
nqp::islt_i($start,0)
?? nqp::clone(self)
!! nqp::slice(self,$start,nqp::sub_i(nqp::elems(self),1))
}

sub INDEX_OUT_OF_RANGE(Int:D $got --> Nil) {
X::OutOfRange.new(what => "Index", :$got, range => "0..^Inf").throw
}
Expand Down

0 comments on commit 3c47f1d

Please sign in to comment.