作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我预计 f1
为 O(i²),f2
为 O(i · log i)。这是怎么回事?
import Data.Set
i = 20000
-- should be slow
f1 = [ x | x <- [1..i] , x `notElem` [2..i-1] ]
-- should be fast
f2 = [ x | x <- [1..i] , x `notMember` fromAscList [2..i-1] ]
ghci 输出:
*Main> f1
[1,20000]
(7.12 secs, 16,013,697,360 bytes)
*Main> f2
[1,20000]
(44.27 secs, 86,391,426,456 bytes)
最佳答案
这只是因为优化尚未发生。如果将以下内容放入文件 F.hs
:
module F (f1,f2) where
import Data.Set
-- should be slow
f1 :: Int -> [Int]
f1 i = [ x | x <- [1..i] , x `notElem` [2..i-1] ]
-- should be fast
f2 :: Int -> [Int]
f2 i = [ x | x <- [1..i] , x `notMember` fromAscList [2..i-1] ]
首先进行优化编译,您将得到以下结果:
$ ghc -O2 F.hs # compile with optimizations
[1 of 1[ Compiling F ( F.hs, F.o )
$ ghci F.hs # now load it up in GHCi
GHCi, version 8.0.1: http://www.haskell.org/ghc/ :? for help
Ok, modules loaded: F (F.o)
Prelude F> :set +s
Prelude F> f1 20000
[1,20000]
(2.16 secs, 2,030,440 bytes)
Prelude F> f2 20000
[1,20000]
(0.05 secs, 4,591,312 bytes)
我的猜测是,在您的情况下,您让 GHCi 多次重新计算 fromAscList [2..i-1]
,或类似的事情。
关于Haskell:Data.Set `notMember` 比 `notElem` 慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39987459/
我预计 f1 为 O(i²),f2 为 O(i · log i)。这是怎么回事? import Data.Set i = 20000 -- should be slow f1 = [ x | x f
我是一名优秀的程序员,十分优秀!