17 May 18:17
Another optimization question
From: Jeroen <yrn001 <at> gmail.com>
Subject: Another optimization question
Newsgroups: gmane.comp.lang.haskell.cafe
Date: 2008-05-17 16:19:42 GMT
Subject: Another optimization question
Newsgroups: gmane.comp.lang.haskell.cafe
Date: 2008-05-17 16:19:42 GMT
Hi, I know there's been quite some performance/optimization post lately,
so I hope there still room for one more. While solving a ProjectEuler
problem (27), I saw a performance issue I cannot explain. I narrowed it
down to the following code (never mind that 'primes' is just [1..],
the problem is the same or worse with real primes):
primes :: [Int]
primes = [1..]
isPrime :: Int -> Bool
isPrime x = isPrime' x primes
where isPrime' x (p:ps) | x == p = True
| x > p = isPrime' x ps
| otherwise = False
main = print $ length (filter (== True) (map isPrime [1..5000]))
$ time ./experiment1
5000
real 0m4.037s
user 0m3.378s
sys 0m0.060s
All good, but if I change isPrime to the simpeler
isPrime x = elem x (takeWhile (<= x) primes)
it takes twice as long:
(Continue reading)
RSS Feed