api-guidelines
api-guidelines copied to clipboard
Methods named `len`, `is_empty` and `capacity` should take constant time
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
Another data point from kdl: https://github.com/kdl-org/kdl-rs/issues/133