(length my-list) - O(n) or O(1) ?
(length my-list) - O(n) or O(1) ?
Does (length) calculate the size of a list by iterating through its elements or is there a value stored somewhere internally?
Re: (length my-list) - O(n) or O(1) ?
I haven't look in C sources of newLISP, but direct timing reveals that answer is O(1). There is another wonder here: '(push elt lst -1)' works in a constant time. Therefore I believe that the pointer to the last element of a list is stored somewhere. But then '(last lst)' works in a linear time. Why? Maybe Lutz will explain?itistoday wrote:Does (length) calculate the size of a list by iterating through its elements or is there a value stored somewhere internally?
With newLISP you can grow your lists from the right side!
Re: (length my-list) - O(n) or O(1) ?
Oops! Wrong! It's O(n)! Very, very evil typo. Sorry, folks. And nobody have corrected me. :-( But you should'n trust me, try it yourself:Cyril wrote:I haven't look in C sources of newLISP, but direct timing reveals that answer is O(1).
Code: Select all
(setq x (sequence 1 (eval-string (main-args 2))))
(setq a (time-of-day))
(setq y (length x))
(setq b (time-of-day))
(println (- b a))
(exit)
With newLISP you can grow your lists from the right side!
Re: (length my-list) - O(n) or O(1) ?
Are you saying that's what I get for trusting you? ;)Cyril wrote:Oops! Wrong! It's O(n)! Very, very evil typo. Sorry, folks. And nobody have corrected me. :-(
Yeah. That's a problem I think... Lutz?