Skip to content

Commit

Permalink
Make native array.sum faster
Browse files Browse the repository at this point in the history
- 1.2x as fast by default by not using Any::sum anymore
- 35x as fast with specifying the :wrap named variable

The latter will do *all* calculations in native ints: should the sum of
the native array exceed the size of the "int" type, then it will silently
wrap.  This may or may not be what you want, hence the optional named variable.
  • Loading branch information
lizmat committed Jul 11, 2018
1 parent 5a9168e commit 88e913b
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions src/core/native_array.pm6
Expand Up @@ -988,6 +988,34 @@ my class array does Iterable {
#- PLEASE DON'T CHANGE ANYTHING ABOVE THIS LINE
#- end of generated part of intarray role -------------------------------------

method sum(intarray:D: :$wrap) {
nqp::if(
(my int $elems = nqp::elems(self)),
nqp::stmts(
(my int $i),
nqp::if(
$wrap,
nqp::stmts(
(my int $sum = nqp::atpos_i(self,0)),
nqp::while(
nqp::islt_i(($i = nqp::add_i($i,1)),$elems),
$sum = nqp::add_i($sum,nqp::atpos_i(self,$i))
),
$sum
),
nqp::stmts(
(my Int $Sum = nqp::atpos_i(self,0)),
nqp::while(
nqp::islt_i(($i = nqp::add_i($i,1)),$elems),
$Sum = $Sum + nqp::atpos_i(self,$i)
),
$Sum
)
)
),
0
)
}
method join(intarray:D: $delim = '') {
my int $elems = nqp::elems(self);
my $list := nqp::setelems(nqp::list_s,$elems);
Expand Down

0 comments on commit 88e913b

Please sign in to comment.