https://wiki.haskell.org/api.php?action=feedcontributions&user=Lazamar&feedformat=atomHaskellWiki - User contributions [en]2019-08-22T15:01:24ZUser contributionsMediaWiki 1.27.4https://wiki.haskell.org/index.php?title=Performance/Strictness&diff=62121Performance/Strictness2017-09-09T17:27:54Z<p>Lazamar: /* Strictness analysis */</p>
<hr />
<div>{{Performance infobox}}<br />
[[Category:Performance|Strictness]]<br />
Haskell is a non-strict language, and most implementations use a strategy called ''laziness'' to run your program. Basically laziness == non-strictness + sharing.<br />
<br />
[[Performance/Laziness|Laziness]] can be a useful tool for improving performance, but more often than not it reduces performance by adding a constant overhead to everything. Because of laziness, the compiler can't evaluate a function argument and pass the value to the function, it has to record the expression in the heap in a ''suspension'' (or ''[[thunk]]'') in case it is evaluated later. Storing and evaluating suspensions is costly, and unnecessary if the expression was going to be evaluated anyway. <br />
<br />
== Strictness analysis ==<br />
<br />
Optimising compilers like GHC try to reduce the cost of laziness using ''strictness analysis'', which attempts to determine which function arguments are always evaluated by the function, and hence can be evaluated by the caller instead. Sometimes this leads to bigger gains; a strict <code-haskell>Int</code-haskell> can be passed as an unboxed value, for example. Strictness analysis sometimes does wonderful things; for example it is very good at optimising <code-haskell>fac</code-haskell>:<br />
<pre-haskell><br />
fac :: Int -> Int<br />
fac n = if n <= 1 then 1 else n * fac (n-1)<br />
</pre-haskell><br />
<br />
Strictness analysis can spot the fact that the argument <code-haskell>n</code-haskell> is strict, and can be represented unboxed. The resulting function won't use any heap while it is running, as you'd expect.<br />
<br />
The common case of misunderstanding of strictness analysis is when [[Fold|folding]] (reducing) lists. If this program<br />
<pre-haskell><br />
main = print (foldl (+) 0 [1..1000000])<br />
</pre-haskell><br />
is compiled in GHC without "-O" flag, it uses a lot of heap and stack. A programmer knows that the long list (<code-haskell>[1..1000000]</code-haskell>) is stored as a thunk, not fully, because the programmer read about [[non-strict semantics]] and [[lazy vs. non-strict]]. The programmer explicitly wrote <code-haskell>sum</code-haskell> as [[Tail recursion|tail recursive]], so the program should use a small amount of stack, because the programmer knows about [[stack overflow]]. So behavior of the program looks mysterious to the programmer.<br />
<br />
The programmer concludes that the program somehow decides to store the long list fully in the heap, or garbage collector is not able to remove dead prefix of the long list. Wrong. The long list is fine.<br />
<br />
Look at the definition from the standard library.<br />
<pre-haskell><br />
foldl :: (a -> b -> a) -> a -> [b] -> a<br />
foldl f z0 xs0 = lgo z0 xs0<br />
where<br />
lgo z [] = z<br />
lgo z (x:xs) = lgo (f z x) xs<br />
</pre-haskell><br />
<br />
<code-haskell>lgo</code-haskell>, instead of adding elements of the long list, creates '''a thunk''' for <code-haskell>(f z x)</code-haskell>. <code-haskell>z</code-haskell> is stored within that thunk, and <code-haskell>z</code-haskell> is a thunk also, created during the previous call to <code-haskell>lgo</code-haskell>. The program creates the long chain of thunks. Stack is bloated when evaluating that chain.<br />
<br />
With "-O" flag GHC performs strictness analysis, then it knows that <code-haskell>lgo</code-haskell> is strict in <code-haskell>z</code-haskell> argument, therefore thunks are not needed and are not created.<br />
<br />
== Limitations of strictness analysis ==<br />
<br />
It's easy to accidentally write functions that aren't strict, though. Often a lazy function can be sitting around eating up your performance, when making it strict wouldn't change the meaning of the program. For example:<br />
<pre-haskell><br />
suminit :: [Int] -> Int -> Int -> (Int,[Int])<br />
suminit xs len acc = case len == 0 of<br />
True -> (acc,xs)<br />
False -> case xs of<br />
[] -> (acc,[])<br />
x:xs -> suminit xs (len-1) (acc+x)<br />
main = print (fst (suminit [1..] 1000000 0))<br />
</pre-haskell><br />
this function sums the first len elements of a list, returning the sum and the remaining list. We've already tried to improve performance by using an [[Performance/Accumulating parameter|accumulating parameter]]. However, the parameter <code-haskell>acc</code-haskell> isn't strict, because there's no guarantee that the caller will evaluate it. The compiler will use a fully boxed <code-haskell>Int</code-haskell> to represent <code-haskell>acc</code-haskell>, although it will probably use an unboxed <code-haskell>Int</code-haskell> to represent <code-haskell>len</code-haskell>. The expression <code-haskell>(acc+x)</code-haskell> will be saved as a suspension, rather than evaluated on the spot. (Incidentally, this is a common pattern we see crop up time and again in small recursive functions with a few parameters).<br />
<br />
== Explicit strictness ==<br />
<br />
We can make an argument strict explicitly.<br />
<br />
In the <code-haskell>foldl</code-haskell> example, replace <code-haskell>foldl</code-haskell> with <code-haskell>foldl'</code-haskell>.<br />
<br />
For <code-haskell>suminit</code-haskell>, we need to make <code-haskell>acc</code-haskell> strict. The way to do this is using <code-haskell>seq</code-haskell>:<br />
<pre-haskell><br />
suminit :: [Int] -> Int -> Int -> (Int,[Int])<br />
suminit xs len acc = acc `seq` case len == 0 of<br />
True -> (acc,xs)<br />
False -> case xs of<br />
[] -> (acc,[])<br />
x:xs -> suminit xs (len-1) (acc+x)<br />
</pre-haskell><br />
<br />
Some other languages (eg. Clean) have strictness annotations on types, which is a less ugly way to express this, but for now there are no Haskell compilers that support this.<br />
<br />
With the <tt>BangPatterns</tt> GHC extension enabled, the above can be written as<br />
<br />
{{Note|For strict data structures, see [[Performance/Data_types]].}}<br />
<br />
<pre-haskell><br />
suminit xs !len !acc = …<br />
</pre-haskell><br />
<br />
Incidentally, GHC will also eliminate the tuple returned by this function if the caller immediately deconstructs it.<br />
<br />
== Evaluating expressions strictly ==<br />
<br />
There's a useful variant of the infix application operator <code-haskell>($)</code-haskell> that evaluates its argument strictly: <code-haskell>($!)</code-haskell>. This can often be used to great effect in eliminating unnecessary suspensions that the compiler hasn't spotted. eg. in a function application<br />
<pre-haskell><br />
f (g x)<br />
</pre-haskell><br />
writing instead<br />
<pre-haskell><br />
f $! (g x)<br />
</pre-haskell><br />
will be more efficient if (a) you were going to evaluate <code-haskell>(g x)</code-haskell> anyway, and (b) <code-haskell>f</code-haskell> isn't visibly strict, or inlined. If <code-haskell>f</code-haskell> is strict or inlined, then the chances are that <code-haskell>($!)</code-haskell> is unnecessary cruft here.<br />
<br />
A good example is the monadic return. If you find yourself writing<br />
<pre-haskell><br />
do …<br />
…<br />
return (fn x)<br />
</pre-haskell><br />
<br />
then consider instead writing<br />
<pre-haskell><br />
do …<br />
…<br />
return $! fn x<br />
</pre-haskell><br />
it is very rare to actually need laziness in the argument of return here.<br />
<br />
Warning: Using any kind of strictness annotations as above can have unexpected impact on program semantics, in particular when certain optimizations are performed by the compiler. See [[correctness of short cut fusion]].<br />
<br />
== Rule of Thumb for Strictness Annotation ==<br />
<br />
A rule of thumb for when strictness annotation might be needed:<br />
<br />
When a function <code-haskell>f</code-haskell> with argument <code-haskell>x</code-haskell> satisfies both conditions:<br />
* <code-haskell>f</code-haskell> calls a function on a function of <code-haskell>x</code-haskell>: <code-haskell>(h (g x))</code-haskell><br />
* is not already strict in <code-haskell>x</code-haskell> (does not inspect <code-haskell>x</code-haskell>'s value), <br />
then it can be helpful to force evaluation:<br />
<br />
Example:<br />
<pre-haskell><br />
-- Force Strict: Make g's argument smaller.<br />
f x = g $! (h x)<br />
<br />
-- Don't force: f isn't building on x, so just let g deal with it.<br />
f x = g x <br />
<br />
-- Don't force: f is already strict in x<br />
f x = case x of <br />
0 -> (h (g x))<br />
</pre-haskell></div>Lazamar