Reading paragraph about head retention in "Clojure Programming" (page 98), i couldn't figure out what happens in split-with
example. I've tried to experiment with repl but it made me more confused.
(time (let [r (range 1e7)
a (take-while #(< % 12) r)
b (drop-while #(< % 12) r)]
[(count a) (count b)]))
"Elapsed time: 1910.401711 msecs"
[12 9999988]
(time (let [r (range 1e7)
a (take-while #(< % 12) r)
b (drop-while #(< % 12) r)]
[(count b) (count a)]))
"Elapsed time: 3580.473787 msecs"
[9999988 12]
(time (let [r (range 1e7)
a (take-while #(< % 12) r)
b (drop-while #(< % 12) r)]
[(count b)]))
"Elapsed time: 3516.70982 msecs"
[9999988]
As you can see from the last example, if I don't compute a
, time consuming somehow grows. I guess, i've missed something here, but what?
Count is O(1). That's why your measurements don't depend on it.
The count
function is O(1) for Counted collections, which includes vectors and lists.
Sequences, on the other hand, are not counted which makes count
O(n) for them. The important part here is that the functions take-while
and drop-while
return sequences. The fact that they are also lazy is not a major factor here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With