[Haskell-beginners] Memory usage of if-then-else vs guards

Miguel Angel Ordoñez Silis mianorsi at ciencias.unam.mx
Fri Feb 14 08:21:06 UTC 2020

Hí everybody,

Earlier today I was testing some code in ghci with ":set +s" enabled. For
some reason I changed an if-then-else expressions to guards and I was
surprised to find out that the memory usage declined significantly (around

Here is a function call output using if-then-else:
λ> inarow1 ls
(1.28 secs, 401,690,400 bytes)

And here is a function call output using guards:
λ> inarow1 ls
(1.18 secs, 313,690,576 bytes)

I ran both versions many times and this difference was consistent. Could
you help me understand why?



P.S. I don't think it should matter but maybe it does, here is the function

inarow1 :: forall a. Eq a => [a] -> Int
inarow1 []     = 0
inarow1 (x:[]) = 1
inarow1 ls     = aux 0 1 ls where
  aux :: Int -> Int -> [a] -> Int
  aux top curr (x:y:[])      = max top $ if x == y then curr + 1 else curr
  aux top curr (x:xs@(y:ys))
    | x == y    = aux top (curr + 1) xs
    | otherwise = aux (max top curr) 1 xs

And the list:
ls = [1..1000000]
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/beginners/attachments/20200214/cc73028d/attachment.html>

More information about the Beginners mailing list