user=> (time (remove nil? [ nil 1 2 nil 4]))
"Elapsed time: 0.065092 msecs"
(1 2 4)
Choose the flavor your prefer...
Luc P.
Glen Rubin <rubi...@gmail.com> wrote ..
> What is the fastest way to remove nils from a sequence?
>
> I usually use the filter function, but I see there are other functions
> like remove that should also do the trick.
>
> --
> You received this message because you are subscribed to the Google
> Groups "Clojure" group.
> To post to this group, send email to clo...@googlegroups.com
> Note that posts from new members are moderated - please be patient with your first
> post.
> To unsubscribe from this group, send email to
> clojure+u...@googlegroups.com
> For more options, visit this group at
> http://groups.google.com/group/clojure?hl=en
Luc P.
================
The rabid Muppet
user=> (time (filter identity [ nil 1 2 nil 4]))
"Elapsed time: 0.053219 msecs"
(1 2 4)
user=> (time (remove nil? [ nil 1 2 nil 4]))
"Elapsed time: 0.065092 msecs"
(1 2 4)
Choose the flavor your prefer...
Luc P.
Mark Engelberg <mark.en...@gmail.com> wrote ..
> (keep identity l) is preferable to (filter identity l)
>
You're not timing the execution, just the construction of a lazy seq:
user> (time (remove nil? (repeat 1000000 nil)))
"Elapsed time: 0.044 msecs"
()
user> (time (doall (remove nil? (repeat 1000000 nil))))
"Elapsed time: 772.469 msecs"
()
-Steve
user> (def nil-seq (doall (interleave (repeat 1e5 nil) (repeat 1e5
"whatever"))) )
#'user/nil-seq
user> (time (doall (keep identity nil-seq)))
"Elapsed time: 122.485848 msecs"
user> (time (doall (remove nil? nil-seq)))
"Elapsed time: 149.71484 msecs"
--Robert McIntyre
I have to run these all a few times before the times quit shrinking
(JITting being done). Then:
user=> (time (do (doall (keep identity nil-seq)) nil))
"Elapsed time: 70.24324 msecs"
nil
user=> (time (do (doall (remove nil? nil-seq)) nil))
"Elapsed time: 40.47016 msecs"
nil
user=> (time (do (doall (filter identity nil-seq)) nil))
"Elapsed time: 36.70256 msecs"
nil
It seems on my system keep identity is actually almost twice as SLOW
as remove nil? and filter identity is slightly faster; filter identity
is almost exactly twice as fast as keep identity. Filter identity
does, of course, discard falses as well as nils, but when that's
acceptable it's worth knowing it's fastest.
I wonder if the difference is that I'm using the -server vm?
It's especially interesting, in light of the likelihood that identity
is probably compiling away to nothing when the JIT is done inlining
everything, that both the slowest and the fastest use identity. It
suggests that keep is inherently somewhat slow, in particular.
I don't know if we can conclude that yet. It seems to be fastest on
one system with one combination of Java version, VM settings, and
clojure version and non-fastest on another system with another
combination of Java version, VM settings, and clojure version.