How to improve Haskell IO performance?

Haskell IO seems to be relatively slow.

For example, comparing Haskell with Python

#io.py import sys s=sys.stdin.read() sys.stdout.write(s) 

 -- io.hs main = do s <- getContents putStr s 

Their performance (gen.py writes 512k of data to stdout):

Python version:

 $ time python gen.py | python io.py > /dev/null real 0m0.203s user 0m0.015s sys 0m0.000s 

Haskell Version:

 $ time python gen.py | runhaskell io.hs > /dev/null real 0m0.562s user 0m0.015s sys 0m0.000s 

Haskell seems to be much lower. Are there any problems with my test? Or is it just an integral Haskell problem?

Thanks.

+6
source share
1 answer

Your example is slow because it uses lazy IO with String -s. Both have their own overhead.

In particular, String is a Char -s linked list, so it has two overhead service words for each character (one word for the constructor tag and one for the direct pointer), and each character takes at least one word (one word for cached low characters, three words for unescaped characters).

Strict I / O with byte or unicode input is much faster. Try the following tests:

 import qualified Data.ByteString as B main = B.putStr =<< B.getContents 

Or the following:

 import qualified Data.Text as T import qualified Data.Text.IO as T main = T.putStr =<< T.getContents 
+6
source

Source: https://habr.com/ru/post/989054/


All Articles