I'm just starting to try to figure out IO and lazy IO in Haskell, and this example I wrote is really slow. It just reads a file of 10M integers and computes the maximum.
import System.IO
maxNum :: [String] -> Int
maxNum = maximum . map getInt
where getInt x = read x :: Int
main = do
inh <- openFile "randints.txt" ReadMode
contents <- hGetContents inh
let myMax = maxNum $ lines contents
putStrLn $ show myMax
The simple Python version I wrote runs about 6 times faster:
inh = open('randints.txt', 'r')
my_max = max(int(line) for line in inh)
print my_max
hGetContents is supposed to be lazy, so I don't think it's reading the whole file into memory first. The profiler shows that 93% of the time is spent in maxNum.getInt, but I'm not experienced enough (or at all) profiling Haskell to figure out whether that's a red herring because of lazy evaluation.
Did I do something wrong that broke the laziness somehow? Or do regular Strings in Haskell just perform that poorly?