Skip to content

Commit

Permalink
Make Date.truncated-to a lot faster
Browse files Browse the repository at this point in the history
- upto 1.6x as fast for truncating to week
- upto 15x as fast for truncating to month
- upto 10x as fast for truncating to year

Also remove now unneeded !truncate-ymd method.
  • Loading branch information
lizmat committed Jan 28, 2021
1 parent e6c0b5e commit c9ac5d9
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 19 deletions.
29 changes: 26 additions & 3 deletions src/core.c/Date.pm6
Original file line number Diff line number Diff line change
Expand Up @@ -217,9 +217,32 @@ my class Date does Dateish {
)
}

method truncated-to(Cool $unit --> Date:D) {
self!clone-without-validating(
|self!truncate-ymd(self!VALID-UNIT($unit)));
method truncated-to(Date:D: str $unit --> Date:D) {
my $truncated := nqp::clone(self);
my $what := self.WHAT;
nqp::bindattr_i($truncated,$what,'$!daycount',0);
nqp::if(
nqp::eqat($unit,'week',0),
($truncated := $truncated.move-by-unit(
'day',
nqp::sub_i(1,$truncated.day-of-week)
)),
nqp::stmts(
nqp::bindattr_i($truncated,$what,'$!day',1),
nqp::unless(
nqp::eqat($unit,'month',0),
nqp::stmts(
nqp::bindattr_i($truncated,$what,'$!month',1),
nqp::unless(
nqp::eqat($unit,'year',0),
die "Cannot truncate {self.^name} object to '$unit'"
)
)
)
)
);

$truncated
}

# workhorse method for moving a Date
Expand Down
16 changes: 0 additions & 16 deletions src/core.c/Dateish.pm6
Original file line number Diff line number Diff line change
Expand Up @@ -202,22 +202,6 @@ my role Dateish {
?? "More than one time unit supplied"
!! die "No time unit supplied";
}

method !truncate-ymd(Cool:D $unit, %parts? is copy) {
if $unit eq 'week' | 'weeks' {
my $new-dc = self.daycount - self.day-of-week + 1;
self!ymd-from-daycount($new-dc,
%parts<year>,%parts<month>,%parts<day>);
}
elsif $unit eq 'day' | 'days' {
# no-op
}
else { # $unit eq 'month' | 'months' | 'year' | 'years'
%parts<day> = 1;
%parts<month> = 1 if $unit eq 'year' | 'years';
}
%parts;
}
}

# =begin pod
Expand Down

0 comments on commit c9ac5d9

Please sign in to comment.