BLOG

Notes from the KAYAC hyper-casual team

When to Use a Linked List (LinkedList)

Takashi Hirayama

Hello. I'm Hirayama from the Technology Department. Today's topic is an unglamorous one. There aren't even any figures.

A few times a year, I find myself wanting to use a linked list (also called a linear list). It's always in textbooks as a basic data structure, but I get the impression that few people actually use it.

In this article I'd like to show, concretely, the kind of situation where it comes in handy.

99% of the time, an array or a dictionary

In my experience writing programs so far, and not just in Unity, an array or a dictionary covers 99% of needs.

"Array" here is in the broad sense, and in C# it includes List as well. A good rule of thumb is List if the count is variable, and an array (in the narrow sense) if it's fixed.

A dictionary is mainly Dictionary, but in cases where you only need keys, you can consider HashSet a kind of dictionary too. And when you want the keys to come out in a particular order when you foreach over them, you use SortedDictionary, which is also a kind of dictionary. Any data structure that can do the three operations of search, insertion and deletion in O(logN) or better can be treated as a dictionary.

SortedDictionary (a search tree inside) is the most capable, so if small speed differences don't bother you, there's no real problem using SortedDictionary for every dictionary. It won't be 5 times slower. In fact, even if you replaced every array with a dictionary, performance wouldn't drop that much. It won't be 10 times slower. In that sense, you could call the dictionary the strongest data structure.

But there are times when even that strongest data structure isn't enough.

A concrete example

I'm currently making a library around AssetBundles, and its download handling includes logic like this:

  • Download items come in three kinds: "downloading", "waiting to download" and "downloaded".
  • The maximum number of "downloading" items is fixed, and their state is monitored every frame. If one has finished, it moves to "downloaded". The oldest "waiting to download" item moves to "downloading".
  • If an item becomes unnecessary while "waiting to download", it is removed from "waiting to download".

So, what data structures should we use?

First, if all three kinds are the same type, it's handy to put them in a dictionary regardless of kind. Look one up by name and there it is.

Dictionary<string, Item> _items;

Let's say the type Item holds the download state. It's a dictionary keyed by string, so you can search for and delete items by name.

Next, "downloading" items are all monitored every frame, so let's give them a separate fixed-size array. Every frame, loop over it with a for loop and check the UnityWebRequests inside. With only 8 or 16 of them, doing this every frame is no problem.

Item[] _goingItems;

"Downloaded" actually has no work to do, so I don't set anything up for it. Whatever is neither "downloading" nor "waiting to download" can be treated as "downloaded".

The data structure for "waiting to download"

The problem is what to use for "waiting to download". Let's start by thinking about the logic. Take this requirement:

  • The maximum number of "downloading" items is fixed, and their state is monitored every frame. If one has finished, it moves to "downloaded". The oldest "waiting to download" item moves to "downloading".

Put into code, it would look something like this:

for (int i = 0; i < _goingItems.Length; i++)
{
    if (_goingItems[i].done)
    {
        _goingItems[i] = ダウンロード待ちの先頭;
        _goingItems[i].StartDownload();
        ダウンロード待ちの先頭を削除;
    }
}
If "downloading" slot i has finished, take one from "waiting to download", move it there, and start the download. Then delete the head of "waiting to download".

Looking at just this part, it feels like a queue would do for "waiting to download". What was requested first should be processed first, so we want the order kept. The standard library's Queue is an array under the hood, made easier to use by adding the restriction "you can only remove from the front and only add at the end". A List or array would also do, but if you want to rule out bugs that touch the middle and keep the code short, Queue is a good choice.

The problem, however, is this one:

  • If an item becomes unnecessary while "waiting to download", it is removed from "waiting to download".

We don't know which one will be removed, so a queue, which doesn't let you get at the middle, won't work. Reluctantly, let's use an array. But removing from the middle of an array is painfully slow.

//assume List<Item> _waitingItems; is defined

int to = 0;
for (int i = 0; i < _waitingItems.Count; i++)
{
    _waitingItems[to] = _waitingItems[i];
    if (_waitingItems[i].name != cancellingName)
    {
        to++;
    }
}
_waitingItems.RemoveRange(to, _waitingItems.Count - to);

Removing from an array while searching it generally ends up like this. List.RemoveAll(Predicate) probably looks like this inside.

We prepare a variable to (the copy destination) and loop, copying element i to position to. to is ++ed for elements we keep, and not ++ed for elements we remove. At the end, RemoveRange reduces the count. If Count is 10 and to is 7, then 3 were removed. The result is an array with the removed elements squeezed out.

If you know there will be few items "waiting to download", this is fine, but as their number grows it gets proportionally slower. What I have in mind is situations like "7,000 items waiting to download", so I can't live with per-frame processing that grows in proportion to that.

Then how about a dictionary? If "waiting to download" were in a dictionary, you could find and remove an item in one go. But that's no good either. Now we can't satisfy "I want to take them out in the order they were put in". The same goes for SortedDictionary. We want them in insertion order regardless of key, so it doesn't help.

A dictionary you can take things out of in insertion order

In other words, what we want is "a dictionary you can take things out of in the order they were put in". The easiest way to make one is a dictionary plus a linked list.

Dictionary<string, Item> _items;
LinkedList<Item> _waitingItems;

class Item
{
    public LinkedListNode<Item> waitingItemsNode;
}
  • Prepare a dictionary you can look up by name (_items)
  • Prepare a linked list (_waitingItems)
  • Add a linked-list node to the data (waitingItemsNode)

The trick is the last one, "record the linked-list node inside the data". Because each item knows where it is in the list, deletion becomes fast. Unlike an array, a linked list can remove from the middle practically for free.

First, let's use LinkedList to turn this into code:

  • The maximum number of "downloading" items is fixed, and their state is monitored every frame. If one has finished, it moves to "downloaded". The oldest "waiting to download" item moves into the freed slot.
for (int i = 0; i < _goingItems.Length; i++)
{
    if (_goingItems[i].done)
    {
        _doneItems.Add(_goingItems[i]);
        _goingItems[i] = _waitingItems.First.Value;
        _waitingItems.RemoveFirst();
    }
}

LinkedList.First gets you the head, but what comes back is a LinkedListNode. This is the class representing "a position in the linked list", and you can pass it in to delete or insert at that position. Here we just need to remove the head and don't need to specify a position, so we take out the Value inside right away. Then RemoveFirst() removes the head.

Next, adding to _waitingItems.

var node = _waitingItems.AddLast(newItem);
newItem.waitingItemsNode = node;

LinkedList.AddLast() adds it at the end, and we remember the returned LinkedListNode inside the data. Using it, let's implement this one:

  • If an item becomes unnecessary while "waiting to download", it is removed from "waiting to download".
Item item;
if (_items.TryGetValue(cancellingName, out item))
{
    _waitingItems.Remove(item.waitingItemsNode);
}

First, look up the item to cancel in the dictionary, using its name as the key. Doing ContainsKey and then taking it out with the indexer searches twice and is slow, so TryGetValue is the way to go.

And if it's found, call LinkedList.Remove() with the LinkedListNode we stored in it. With that, every operation is O(1). Even if "waiting to download" grows to tens of thousands of files, it doesn't get slower.

Making it efficient

The implementation above is the basic version; if I were writing it for real, I wouldn't leave it like this. Why? Because every addition to the LinkedList needs a new LinkedListNode, which hurts performance.

So what do we do?

Let your own data type act as a LinkedListNode itself.

class Item
{
    //public LinkedListNode<Item> waitingItemsNode; drop this
    public Item waitingItemsNext;
    public Item waitingItemsPrev;
}

Instead of holding a LinkedListNode, each Item holds references to the previous Item and the next Item. Then you just implement a few linked-list operations. In other words, you don't use LinkedList either; you write your own.

Writing your own sounds like a lot, but in this example only two operations are needed:

  • Add at the end
  • Remove from any position

so the implementation is easy. It looks like this:

// replace LinkedList<Item> _waitingItems; with the following two lines
Item _waitingListFirst; // head
Item _waitingListLast; // tail

void AddLastToWaitingList(Item item)
{
    _waitingListLast.waitingItemsNext = item;
    item.waitingItemsPrev = _waitingListLast;
    // TODO: handle the case where the list is empty separately!
}

void RemoveFromWaitingList(Item item)
{
    var prev = item.waitingItemsPrev;
    var next = item.waitingItemsNext;
    prev.waitingItemsNext = next;
    next.waitingItemsPrev = prev;
    // TODO: handle removing the head or the tail separately!
}

Adding the very first item, or removing the head or tail, needs special care, but it's just null checks and branches, so if you carefully separate the cases it isn't hard. If that's a pain, prepare one dummy element at the head and one at the tail that are never removed (a technique called a sentinel). Then you don't need the branches.

For all my talk about efficiency, the library I'm making still uses LinkedList. If it goes into real use and I'm told "there's a lot of GCAlloc, do something about it", I'll do something, and at that point I'll probably also make instances of the type corresponding to Item above reusable.

By the way, this kind of efficiency isn't limited to linked lists. The UI element base class in the implementation of the debug UI I wrote about before is not only an element of a linked list but also an element of a tree structure, holding references to its parent and children too. Take a look if you're interested. At that level, using the containers provided by .NET as they are would mean new everywhere and more complicated code, so it's quicker to write your own.

As an aside, linked lists also have the interesting property that you can merge sort them without extra space. Merge sort has the handy property that "the order of elements with equal values doesn't change", but doing it on an array eats extra memory, which is a hassle. With a linked list, though, you can choose merge sort without hesitation. In the current example, if you want something like "sort the waiting downloads by size, but among equal sizes give priority to the older one", a merge sort gives you that automatically.

In closing

When arrays and dictionaries fall short, I think it's good to have the linked list as an option. "A dictionary you want to access in insertion order" is one example.

Also, the problem of linked lists causing frequent GCAlloc is solved by letting your own data type serve as an element of the linked list itself. This technique is also called an intrusive linked list.

And it's not just linked lists: data structures in general are handy when you know how to use them, so I think it's good to keep them in the toolbox in your head, ready to pull out any time. For example, here's roughly what's in my toolbox:

  • Fixed-size array (Array): first consider whether this is enough
  • Variable-size array (List): use this if the count varies, but if the operations you need are limited, consider a queue or a stack
  • Queue (Queue): use this if you never need to touch the middle and take things out in insertion order
  • Stack (Stack): usually this when pooling something. Among the variable-size-array types it's the most restrictive, so it's less prone to bugs, and fast.
  • Linked list (LinkedList): use this alongside when you want to give an order to things already in another data structure
  • Hash (Dictionary): first choice when you need search
  • Keys-only hash (HashSet): when you don't need the Value of a Dictionary. If you just want to remove duplicates, sorting an array keeps memory cleaner.
  • Search tree (SortedDictionary): the one to use when you want a dictionary you can loop over in key order.
  • Tree: rather than holding an array of children, the "first child and next sibling" form is usually more efficient. Don't hold a parent reference if you don't need it.
  • Heap: when pooling something, use this rather than a Stack when you want to order them by some value.

It's probably not obvious where you'd use the last one, the heap, so let me add a note. A heap has the property that "the minimum (or maximum) can be found quickly", and that's what you take advantage of.

For example, say "we've prepared 64 AudioSources for sound effects, and when they're all in use and a new sound can't play, we want to stop the sound that will finish soonest and use its slot". If you build a heap keyed on "end time", you don't need to look at all 64 to find the minimum, so it's fast. Sounds that have finished naturally have small "end times" too, so simply finding a free slot gets faster as well.

The heap isn't in the standard library either, so you write your own, but like a linked list it's a "data structure connected by references", so if your own data type holds references to its left and right children, you can implement a heap without extra GCAlloc.

That said, with only 64 or so, I think you could just check them all to find the minimum.

Bonus

I've put sample code for an IntrusiveList on GitHub. There's a version with sentinels and a version without. Using sentinels cuts the code down a lot and makes it run faster, but needs 2 extra GCAllocs. Note that it compiles, but I haven't actually tested that it runs.

In practice, abstracting it like this hurts performance, and usually you only need a limited set of operations, so I think it's better to write it out plainly for each type that needs it.