[Haskell-beginners] Function application versus function composition performance

Ertugrul Söylemez es at ertes.de
Wed Jun 20 01:10:03 CEST 2012


Matt Ford <matt at dancingfrog.co.uk> wrote:

> So is this true, are composite functions simplified in Haskell in
> general so that they may have improved performance over function
> application?

You may be forgetting that Haskell is lazily evaluated.  If you have
seen the output of compilers for strict languages like C you may find
yourself somewhere between surprised and shocked to see what a Haskell
compiler produces.  The result is not a set of procedures, but a graph
and the less nodes the higher the performance.

To answer your question:  A completely naive compiler will produce the
most efficient code for function application.  That's three nodes, one
for the application node, one for the function, one for the argument.
In that sense function application is in a sense an "atom".  In the case
of applying two functions the result will be five nodes.

On the other hand the function composition operator is compiled to what
is called a supercombinator.  Still assuming the entirely naive compiler
the result will be a graph of seven nodes.  The explanation is that
first you apply the supercombinator, which is five nodes already.  The
result of that is then applied to the argument.  That makes seven nodes.

In your case a function is composed with itself, so in either case
sharing applies, eliminating one node.

Of course this is not what actually happens when you use a compiler like
GHC.  As KC noted the compiler is free to perform certain
transformations that don't change the semantics of the program (one of
the nice features of pure languages).  The produced code is the same in
either case.  If you want to see what is actually produced, have a look
at the core output (see the ghc-core package).

Bottom line:  It doesn't matter whether you use nested application or
composition.


Greets,
Ertugrul

-- 
Not to be or to be and (not to be or to be and (not to be or to be and
(not to be or to be and ... that is the list monad.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 836 bytes
Desc: not available
URL: <http://www.haskell.org/pipermail/beginners/attachments/20120620/ad64776a/attachment.pgp>


More information about the Beginners mailing list