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

Conversation

nik-rev
Copy link

@nik-rev nik-rev commented Jul 25, 2025

Today, I wanted to switch to using Vec::with_capacity instead of Vec::new while iterating over a toml_edit::Table:

let v = Vec::with_capacity(table.len());

But to my surprise, the Table::len method actually takes O(n) time, as it is implemented with Iterator::count:

/// Returns the number of non-empty items in the table.
pub fn len(&self) -> usize {
    self.iter().count()
}

/// Returns true if the table is empty.
pub fn is_empty(&self) -> bool {
    self.len() == 0
}

This is surprising and can make people's code slower, without them realizing why. Library authors should choose different names for a len method if it doesn't take constant time, such as count.

I found a discussion about this from 2017, and decided to open a PR to add this guideline

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant