Skip to content

Methods named len, is_empty and capacity should take constant time #288

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions src/predictability.md
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,26 @@ so on for the other traits.

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

<a id="c-constant-time-methods"></a>

## Methods `len`, `is_empty` and `capacity` take constant time (C-CONSTANT-TIME-METHODS)

The [time complexity] for methods named `len`, `is_empty` and `capacity` should be **O(1)** -
it should always take the same amount of time to run these methods regardless of
how large the collection is.

If you need to count elements by iterating, choose a different name for your methods such as `count` or `size`

### Examples from the standard library

- [`Vec::len`](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.len)
- [`Vec::is_empty`](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.is_empty)
- [`Vec::capacity`](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.capacity)
- [`HashMap::len`](https://doc.rust-lang.org/std/collections/struct.HashMap.html#method.len)
- [`HashSet::capacity`](https://doc.rust-lang.org/std/collections/struct.HashSet.html#method.capacity)
- [`LinkedList::is_empty`](https://doc.rust-lang.org/std/collections/struct.LinkedList.html#method.is_empty)

[time complexity]: https://en.wikipedia.org/wiki/Time_complexity

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