[Haskell-cafe] Code review: efficiency question

Bulat Ziganshin bulat.ziganshin at gmail.com
Tue May 2 04:30:34 EDT 2006


Hello Brian,

Tuesday, May 2, 2006, 3:12:48 AM, you wrote:

>           -- Prolog style coding...
>           drawModals :: [Control] -> ManagerM ()
>           drawModals [] = return ()
>           drawModals (c:cs) = do
>                                                drawModals cs
>                                                drawModal c

imho, it's typical functional style, but without using higher-level
functions

>     mapM_ drawModal (reverse cs)

> However, while this looks more elegant, it is less efficient?
> In other words, how much optimization can one assume when writing Haskell
> code?

ghc will don't translate your later code into the former one. although
in general ghc (but not other haskell compilers, afaik) is very good
in replacing one code with another faster one and in particular in
translating "list producer + list consumer" into straightforward loop

how about this solution:

reverseMapM_ f (x:xs) = do reverseMapM_ f xs; f x
reverseMapM_ f []     = return ()

or you can define `reverseMapM_` via fold, if you have better FP
skills than me :)

> I'm trying to get a rough idea so I can decide whether to write helper
> functions such as drawModals in future or whether I should always just use
> the most elegant code instead.

> Any ideas?

you will laugh, but speed of your two solutions depends on so many
factors (including size of CPU cache) that noone can say that is
better in general. although for small lists reverseMapM_ should be
faster than reverse+mapM. what will be faster - using of higher-order
function or direct recursion, i can't say, it's a really
counter-intuitive area of ghc optimizer :)

of course, i don't think that all that really matters for your program
(drawing should anyway need much more time than looping). just use
higher-level approach (that makes code simpler to write, understand
and maintain) and don't bother your mind :)


-- 
Best regards,
 Bulat                            mailto:Bulat.Ziganshin at gmail.com



More information about the Haskell-Cafe mailing list