Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the runtime complexity of Vec::len?

Tags:

rust

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)

like image 966
kevlarr Avatar asked Apr 11 '18 12:04

kevlarr


1 Answers

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

pub fn len(&self) -> usize {
    self.len
}
like image 165
Yury Tarabanko Avatar answered Oct 17 '22 17:10

Yury Tarabanko