Ronald Schmidt
Sep 3, 2018 · 2 min read

On my MacBook Pro the above code takes 13.3 seconds to run. Not a speed daemon, perhaps, but the code runs and completes,

You seem to imply you are concerned about performance, but Perl 6 speed may not look so bad after a little consideration. You are counting up to a pretty big number and many calculations will use integers too large for native integer arithmetic. I tried a version of your algorithm with Perl 5 and the Math::Prime::Util module, which was quite a bit faster if it could use GMP but much slower with the library disabled by setting MPU_NO_GMP=1in the environment. My Java experience is limited but I think I came up with a reasonably simple Java JDK 8 implementation using java.math.BigInteger which ran somewhat slower than Perl 6 on tio.run and several times slower on my system. A Perl 6 coding and Rakudo using the JVM performed similarly to the Java implementation (also tested on my computer).

I got a modest performance improvement of something like 1/3 less time (40% as of August release) by adding a hyper to your grep code as follows:

my @list = lazy (1, 1, * + * … *).hyper.grep({ .is-prime });
say @list[23];

There was an issue that prevented grep and hyper from working properly together in some versions of Rakudo: https://github.com/rakudo/rakudo/issues/1740

Looking at the output of perl6 --profile, it looks like almost all of the computation time is taken up by the .is-primetest (“exclusive time” of 98%). MoarVM seems to use LibTomMath instead of GMP for multi-precision integer math and GMP seems to be faster. Perhaps there will be future interest in GMP interface libraries and other integration for Perl 6 to match Perl 5.

Java implemetation on tio.run: https://bit.ly/2LRw4C8 (30 sec)
Perl 5 implementation on tio.run: https://bit.ly/2wHEs1q (5 sec)
Perl 6 with hyper on tio.run for comparison: https://bit.ly/2PuDsWd (16 sec)

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade