That really depends on the list. For a normal, lazily evaluated list of Int
s on my computer, I see this function running in about 2 seconds for 10^9 elements, 0.2 seconds for 10^8, and 0.3 seconds for 10^7, so it appears to run in linear time. You can check this yourself by passing the flags +RTS -s -RTS
to your executable when running it from the command line.
I also tried running it with more cores, but it doesn't seem to do anything but increase the memory usage a bit.
An added bonus of the lazy computation is that you only make a single pass over the list. filter
and length
get turned into a single loop by the compiler (with optimizations turned on), so you save memory and efficiency.
count needle haystack = foldl' (\acc elem -> if elem == needle then acc+1 else acc) 0 haystack
. – kqr