Santa has a special treat: a teaser if you will. A part of a chapter from the upcoming book “Migrating Perl to Raku”, to be published January 2020.

Optimization Considerations

If you are an experienced Perl programmer, you have (perhaps inadvertently) learned a few tricks to make execution of your Perl program faster. Some of these idioms work counter-productively in Raku. This chapter deals with some of them and provides the alternative idioms in Raku.

Blessed Hashes Vs. Objects

Objects in Perl generally consist of blessed hashes. As we’ve seen before, this implies that accessors need to be made for them. Which means an extra level of indirection and overhead. So many Perl programmers “know” that the object is basically a hash, and access keys in the blessed hash directly.

Consequently, many Perl programmers decide to forget about creating objects altogether and just use hashes. Which is functionally ok if you’re just using the hash as a store for keys and associated values. But in Raku it is better to actually use objects for that from a performance point of view. Take this example where a hash is created with two keys / values:

# Raku for ^1000000 { # do this a million times my %h = a => 42, b => 666; } say now - INIT now; # 1.4727555

Now, if we use an object with two attributes, this is more 4x as fast:

# Raku class A { has $.a; has $.b; } for ^1000000 { my $obj = A.new(a => 42, b => 666); } say now - INIT now; # 0.3511395

But, you might argue, accessing the keys in the hash will be faster than calling an accessor to fetch the values?

Nope. Using accessors in Raku is faster as well. Compare this code:

# Raku my %h = a => 42, b => 666; for ^10000000 { # do this ten million times my $a = %h<a>; } say now - INIT now; # 0.4713363



To:

# Raku class A { has $.a; has $.b; } my $obj = A.new(a => 42, b => 666); for ^10000000 { my $a = $obj.a; } say now - INIT now; # 0.36870995

Note that using accessors is also faster, albeit not much, but still significantly so.

So why is the accessor method faster in Raku? Well, really because Raku is able to optimise to attributes in an object to a list, easily indexed by a number internally. Whereas for a hash lookup, the string must be hashed before it can be looked up. And that takes a lot more work than just a lookup by index.

Of course, as with all benchmarks, this is just a snapshot in time. Optimisation work continues to be performed on Raku, which may change the outcome of these tests in the future. So, always test yourself if you want to be sure that some optimisation is a valid approach, but only if you’re really interested in squeezing performance out of your Raku code. Remember, premature optimisation is the root of all evil!

Santa hopes you liked it.