Skip to content

Commit 9adf51a

Browse files
committed
[CaR Grant] Show examples of autoboxing issues
and how to deal with them
1 parent 51e79cb commit 9adf51a

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

doc/Language/numerics.pod6

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -574,6 +574,32 @@ say 42 foo 42; # OUTPUT: «full␤»
574574
say 42 foo my int $ = 42; # OUTPUT: «native␤»
575575
=end code
576576
577+
The second relevance of auto-boxing is when you're using native types for performance gains.
578+
If the code you're using results in a lot of auto-boxing being performed you might get I<worse>
579+
performance with native types than you would with non-natives:
580+
581+
=begin code
582+
my $a = -42;
583+
my int $a-native = -42;
584+
{ for ^1000_000 { $a.abs }; say now - ENTER now } # OUTPUT: «0.38180862␤»
585+
{ for ^1000_000 { $a-native.abs }; say now - ENTER now } # OUTPUT: «0.938720␤»
586+
=end code
587+
588+
As you can see above, the native variant is more than twice slower. The reason is the method
589+
call requires the native type to be boxed, while no such thing is needed in the non-native
590+
variant, hence the performance loss.
591+
592+
In this particular case, we can simply switch to a subroutine form of L<abs>, which can work
593+
with native types without boxing them. In other cases, you may need to seek out other solutions
594+
to avoid excessive autoboxing, including switching to non-native types for a portion of the code.
595+
596+
=begin code
597+
my $a = -42;
598+
my int $a-native = -42;
599+
{ for ^1000_000 { abs $a }; say now - ENTER now } # OUTPUT: «0.38229177␤»
600+
{ for ^1000_000 { abs $a-native }; say now - ENTER now } # OUTPUT: «0.3088305␤»
601+
=end code
602+
577603
=head1 Numeric Infectiousness
578604
579605
Numeric "infectiousness" dictates the resultant type when two numerics of different types are

0 commit comments

Comments
 (0)