tech.lgbt is one of the many independent Mastodon servers you can use to participate in the fediverse.
We welcome all marginalized identities. This Mastodon instance is generally for folks who are LGBTQIA+ and Allies with an interest in tech work, academics, or technology in general.

Server stats:

2.9K
active users

Public

I'm trying to get into #rustlang. I've already rewritten a small program and it was an okay experience but today, I hit something weird.

I have a LinkedList and need to iterate over it and, if I found any item that meets some criteria, I need to remove it from the list.

Using C++ iterators, this would be O(N).

Rust's linked_list has an issue [github.com] open for more than 4 years (!) to add a remove function to linked lists. But even with that function, you'll need an index of the item to be removed and cannot (as far as I can tell) use the iterator you already have from scanning the list.

So in Rust I would need to spend O(N) to scan the list and an additional O(N) for each item I need removed.

Or is there a faster way to do that?

GitHubTracking Issue for linked_list_remove · Issue #69210 · rust-lang/rustBy BijanT

@martin huh, i never even knew Rust had a linked list in the stdlib. i wonder what the usecase is over Vec/VecDeque - the docs only say to prefer Vec/VecDeque "almost always" without any info on when to actually use a linked list

Public

@laund [tech.lgbt] In my experience, LinkedLists are great when the container is growing and shrinking dynamically or when you want to move stuff around within the collection while the rest of the items maintain their order. The downside is expensive random access to elements so list are better suited for use cases where you have to iterate through the collection anyways.

Vectors are better for access to random elements and if you know the size of the collection beforehand. It's also cheaper to insert elements at the end if the vector's current size can hold another element. Inserting elements anywhere other than the end or removing an element that is not at the front or back is ridiculously expensive.

Public

@martin i mean i kinda understand that, i just found it interesting the docs don't state this.

Though i kinda wanna do a benchmark of linked list inserting/removing elements in the middle vs vec = vec.iter().filter(remove_condition).collect() - how many elements do i need to filter out for a Vec to be faster? how much slower is iteration of linked lists?

theres a old benchmark by matklad which inserts random numbers into a sorted vec/list, which requires tons of insertions in the middle, that claims Vec is still far more performant at this.

Vev: 33365 μs
List: 184282 μs
github.com/matklad/vec-vs-list
but this was 8 years ago with a different linked list.

GitHubGitHub - matklad/vec-vs-list: Compare vector vs linked list in terms of performanceCompare vector vs linked list in terms of performance - matklad/vec-vs-list