Skip to content

Commit

Permalink
Make Baggy.roll()/pick() about 10% faster
Browse files Browse the repository at this point in the history
Specifically on larger Bags/Mixes
  • Loading branch information
lizmat committed Oct 30, 2016
1 parent 4986d68 commit fc47bbf
Showing 1 changed file with 14 additions and 15 deletions.
29 changes: 14 additions & 15 deletions src/core/Baggy.pm
Expand Up @@ -435,22 +435,21 @@ my role Baggy does QuantHash {

proto method roll(|) { * }
multi method roll(Baggy:D:) {
my Int $rand = self.total.rand.Int;
my Int $seen = 0;
my \iter := nqp::iterator(nqp::getattr(%!elems,Map,'$!storage'));

nqp::while(
iter,
nqp::stmts(
nqp::shift(iter),
($seen = $seen + nqp::iterval(iter).value),
nqp::if(
$seen > $rand,
return nqp::iterval(iter).key
)
nqp::stmts(
(my Int $rand = self.total.rand.Int),
(my Int $seen = 0),
(my \iter := nqp::iterator(nqp::getattr(%!elems,Map,'$!storage'))),
nqp::while(
iter && ($seen = $seen + nqp::getattr(
nqp::iterval(nqp::shift(iter)),Pair,'$!value')) <= $rand,
nqp::null
),
nqp::if(
$seen > $rand,
nqp::getattr(nqp::iterval(iter),Pair,'$!key'),
Nil
)
);
Nil
)
}
multi method roll(Baggy:D: $count) {
nqp::istype($count,Whatever) || $count == Inf
Expand Down

0 comments on commit fc47bbf

Please sign in to comment.