[Haskell-beginners] Pattern matching vs bit twiddling?

Felipe Lessa felipe.lessa at gmail.com
Fri Jul 9 10:27:52 EDT 2010


On Fri, Jul 9, 2010 at 11:15 AM, Patrick LeBoutillier
<patrick.leboutillier at gmail.com> wrote:
> Now I find my code is much clearer (it almost writes itself...) and
> practically absent of low-level bit operations (except, for example,
> converting a Word into an actual Haskell Int32 to perform the actual
> arithmetic). However, I'm wondering about the cost of all the
> "packing/unpacking" via pattern-matching and/or accessors. Perhaps I
> should not worry about this and optimize later if required? Is this
> type of premature optimization (assuming the previous version was
> faster...) really the root of all evil?

Yes, you should test before worrying too much about it.  There's only
one bit you should do regardless: use strict and unpacked fields.  For
example:

data Word = Word !Sign {-# UNPACK #-} !Byte
                       {-# UNPACK #-} !Byte
                       {-# UNPACK #-} !Byte
                       {-# UNPACK #-} !Byte

This should give you boost.  I didn't give an UNPACK pragma to Sign
because AFAIK it won't unpacked anyway.

Of course there's a performance penalty, but if it matters or not
you'll find only by testing.

One possible solution is to never use pattern matching, only
accessors.  That way the code will work for any representation you
choose.  In fact, all bit-fiddling will be contained in your
accessors.

Cheers! =)

-- 
Felipe.


More information about the Beginners mailing list