Skip to content

IndexMap sometimes reports a lower capacity after removing elements #183

Description

@tesselode

I made a small test script that adds and removes elements from an IndexMap:

use indexmap::IndexMap;

fn main() {
	let mut map = IndexMap::with_capacity(10);
	for i in 0..1000 {
		map.insert(i, i);
		println!("{} / {}", map.len(), map.capacity());
		if i % 5 == 0 {
			map.swap_remove_index(i / 2);
			map.swap_remove_index(i / 3);
			map.swap_remove_index(i / 4);
		}
	}
}

Sometimes, when the length of the map (left) decreases, the capacity (right) decreases as well.

410 / 431
411 / 432
412 / 432
413 / 432
411 / 431
412 / 431
413 / 431
414 / 432
415 / 432
414 / 430
415 / 430
416 / 430
417 / 430
418 / 431
416 / 429
417 / 429
418 / 429
419 / 430
420 / 430
419 / 429
420 / 429
421 / 429
422 / 430
423 / 430
421 / 427
422 / 427
423 / 427
424 / 427
425 / 427

From what I understand, the "capacity" is the total number of elements the map can hold in the chunk of memory it has allocated. If you add an item when the map is full, I would expect the capacity to increase as the map allocates more memory. I would never expect the capacity to decrease.

This behavior occurs with both swap_remove_index and shift_remove_index.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions