Skip to content

Commit 762f367

Browse files
authored
Methods named len, is_empty and capacity should take constant time
1 parent 97a0969 commit 762f367

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

src/predictability.md

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,26 @@ so on for the other traits.
131131

132132
[`std::ops`]: https://doc.rust-lang.org/std/ops/index.html#traits
133133

134+
<a id="c-constant-time-methods"></a>
135+
136+
## Methods `len`, `is_empty` and `capacity` take constant time (C-CONSTANT-TIME-METHODS)
137+
138+
The [time complexity] for methods named `len`, `is_empty` and `capacity` should be **O(1)** -
139+
it should always take the same amount of time to run these methods regardless of
140+
how large the collection is.
141+
142+
If you need to count elements by iterating, choose a different name for your methods such as `count` or `size`
143+
144+
### Examples from the standard library
145+
146+
- [`Vec::len`](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.len)
147+
- [`Vec::is_empty`](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.is_empty)
148+
- [`Vec::capacity`](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.capacity)
149+
- [`HashMap::len`](https://doc.rust-lang.org/std/collections/struct.HashMap.html#method.len)
150+
- [`HashSet::capacity`](https://doc.rust-lang.org/std/collections/struct.HashSet.html#method.capacity)
151+
- [`LinkedList::is_empty`](https://doc.rust-lang.org/std/collections/struct.LinkedList.html#method.is_empty)
152+
153+
[time complexity]: https://en.wikipedia.org/wiki/Time_complexity
134154

135155
<a id="c-deref"></a>
136156
## Only smart pointers implement `Deref` and `DerefMut` (C-DEREF)

0 commit comments

Comments
 (0)