14

Given a vector...

let v = vec![1, 2, 3, 4, 5];

Is calling v.len() O(1) or O(n)?


Neither "The Book" (from what I can tell so far) nor the docs mention whether .len() is constant time or not, and I cannot find anything on Stack Overflow or elsewhere.

I'm assuming it's O(1) since [], .push(), and .pop() all are, but I want to be sure before I litter my code with v.len().

I know that I can easily just store/reference the return of len but in some situations - like inner functions - I don't want to keep having to pass both a vector and an int around.

Thanks to @Stargateur for pointing out that indexing's O(1) is different from push/pop's amortized O(1)

7
  • 2
  • @YuryTarabanko Ugh, embarrassing... I had a hard time finding that one... Can you post that as an answer please?
    – kevlarr
    Apr 11, 2018 at 12:58
  • 6
    @kevlarr: Nothing embarrassing here; except for the Docs of course. It would indeed be nice that the complexity of each collection method was made explicit in its doc. I mean, the implementation of len is easy here, but what's the complexity of drain_filter? Apr 11, 2018 at 13:05
  • @MatthieuM. good point!
    – kevlarr
    Apr 11, 2018 at 13:13
  • 4
    push() is not O(1) but amortized O(1), sometime the resize need O(n)
    – Stargateur
    Apr 11, 2018 at 16:00

1 Answer 1

16

It is O(1) as of the implemented code in Rust 1.25.0:

pub fn len(&self) -> usize {
    self.len
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.