Opened 4 years ago

Closed 4 years ago

#10825 closed bug (duplicate)

Poor performance of optimized code.

Reported by: AndriusS Owned by: bgamari
Priority: normal Milestone:
Component: Compiler Version: 7.8.4
Keywords: Cc: floppycat@…
Operating System: Unknown/Multiple Architecture: Unknown/Multiple
Type of failure: Runtime performance bug Test Case:
Blocked By: Blocking:
Related Tickets: #1168 Differential Rev(s):
Wiki Page:


This is possible duplicate of #8814, #8835. I am creating new ticket as I have fairly small example with no dependencies.

The problem is that optimized code runs orders of magnitude slower than non-optimized.

import System.IO.Unsafe (unsafePerformIO)

newtype MyList = MyList Int

equalsLast :: MyList -> Int -> Bool
equalsLast (MyList value) = (== value)

fromList :: [Int] -> MyList
fromList = MyList . last

{- minimizing imports -}
(<$>) = fmap
replicateM' n x = sequence (replicate n x)

readInt = read <$> getLine :: IO Int

readAndMap :: Int -> (Int->Bool) -> IO [Bool]
readAndMap n f = replicateM' n (f <$> readInt)
{- if readAndMap is replaced by commented out line below, the problem goes away -}
--readAndMap n f = map f <$> replicateM' n (readInt)

fromList' :: [Int] -> MyList
{- an attempt to further demostrate the issue. fromList'=fromList is very slow as well -}
fromList' list = unsafePerformIO $ do
    putStrLn "fromList"
    return $ fromList list

readMyList :: Int -> IO MyList
readMyList n = fromList' <$> (replicateM' n $ read <$> getLine)

main :: IO ()
main = do
    n1 <- read <$> getLine :: IO Int
    n2 <- read <$> getLine :: IO Int
    l <- readMyList n1
    ans <- readAndMap n2 (equalsLast l)
    mapM_ print ans

If this code is compiled with no flags, it prints "fromList" once and runs in 0.3s. Compiled with "-O" prints "fromList" many times and takes over 6 seconds.

Here's a Haskell script to generate input for program above:

main = sequence_ $ map print (n:n:[1..n]++[1..n]) where n = 10000

Change History (4)

comment:1 Changed 4 years ago by bgamari

Owner: set to bgamari

Ooh, this looks like a very nice case to put on my performance-related-issues queue.

Thanks for the small testcase.

comment:2 Changed 4 years ago by rwbarton

Does -fno-state-hack make a difference? Since I see replicateM stuff.

comment:3 in reply to:  2 Changed 4 years ago by AndriusS

Yes, with -fno-state-hack everything works fine. This is probably a duplicate of #1168.

comment:4 Changed 4 years ago by thomie

Resolution: duplicate
Status: newclosed
Note: See TracTickets for help on using tickets.