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)
It is O(1)
as of the implemented code in Rust 1.25.0:
pub fn len(&self) -> usize {
self.len
}
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