Why is linear haskell’s quicksort not quicker than the naive approach?
linear-base/examples/Simple/Quicksort.hs at master · tweag/linear-base (github.com)
I get the quicksort module above, and write the following test script.
import Quicksort
import Control.DeepSeq
import System.Random.SplitMix
import Control.Monad
import Control.Monad.State.Strict
import GHC.IO (evaluate)
import System.TimeIt (timeIt)
import Data.List (sort)
len = 5000000 :: Int
gen = mkSMGen 123546789
randomList :: [Int]
randomList = evalState (replicateM len (state nextInt)) gen
qs :: Ord a => [a] -> [a]
qs [] = []
qs (x:xs) = qs ltx ++ x : qs gex
where
ltx = [y | y <- xs, y < x]
gex = [y | y <- xs, y >= x]
deepEval_ :: NFData a => a -> IO ()
deepEval_ = void . evaluate . force
main :: IO ()
main = do
deepEval_ randomList
timeIt $ deepEval_ (quickSort randomList)
timeIt $ deepEval_ (qs randomList)
timeIt $ deepEval_ (sort randomList)
-- CPU time: 29.16s
-- CPU time: 23.14s
-- CPU time: 34.23s
It turns out that the naive approach runs faster than the linear version. Why is that?
(By the way, why is sort in Data.List slowest?)