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:
|
Now, if we use an object with two attributes, this is more 4x as fast:
|
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:
|
To:
|
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.