Post · 21 min read· pp. 81–99

Efficient trie representation

Trie is a multi-way tree, where each edge is labelled with a single letter. In this text several trie representations are shown.

The article is the side effect of work on the pyahocorasic module.

Contents

Introduction

Each node of a tree store two kinds of data: user data and trie-related data. Let say an alphabet has at most 256 letters, thus a letter could be saved on a byte.

During maintaining tree structure following issues appear:

  • Amount of memory required to store nodes and edges.
  • Internal memory fragmentation in underlying dynamic memory allocation routines (malloc/free), that makes real size of tree larger. If small object are allocated/reallocated fragmentation could be significant.
  • Dynamic allocation/reallocation scatters data on a heap, making cache misses visible. Using arrays may improve memory locality.
  • Data alignment in nowadays CPUs is important, making reading and writing memory faster. Structure of node could be packed to fill the smallest possible memory at cost of speed.
  • Time required to retrieve a child node depending on a letter (edge label):
    • const (arrays),
    • logarithmic (arrays) or,
    • linear (arrays, lists).

In experiments Polish, English, French and German words lists were used. User data has got two pointers, i.e. additional 8 bytes per node.

listwordstrie nodes
english138 622312 855
german162 032610 470
french629 4201 297 080
polish3 588 7295 933 658

The sample program were linked against GNU libc, and procedure malloc_stats from malloc.h was used to obtain statistics about the real memory usage.

Simple layouts

Array of all possible edges [version 1]

(image)

The simplest solution is to store all possible pointers to children nodes in array of constant size. C-structure:

text
struct TrieNode {
        /* user data */

        struct TrieNode* children[256];
}

Procedure that returns child node or NULL depending on a letter works in constant time:

text
TrieNode* NEXT(TrieNode* node, uint8_t letter) {
        return node->children[letter]
}

Cons

  • Huge memory requirements — size of node 256 * size of pointer + size of user data.

Pros

  • Very simple implementation and use.
  • Theoretically constant time addressing, but because of large data cache misses may be visible.

Experiment results

languagenode size [bytes]trie size [bytes]bytes/nodeallocated [bytes]wasted [bytes]wasted [%]
english1,032322,866,3601032.00325,369,2162,502,8560.77
german1,032630,005,0401032.00634,888,8164,883,7760.77
french1,0321,338,586,5601032.001,348,963,21610,376,6560.77
polishn/an/an/an/an/an/a

Pointer to array of all possible edges [version 1a]

Instead of a static array of pointers allocate such array only when needed, i.e. leaf nodes don't occupy much memory. This cost additional test when accessing children.

Node structure:

text
struct TrieNode {
        /* user data */

        struct TrieNode** children;
}

Next function:

text
TrieNode* NEXT(TrieNode* node, uint8_t letter) {
        if (node->children)
                return node->children[letter];
        else
                return NULL;
}

Pros

  • smaller memory, but still large

Experiments results

languagenode size [bytes]trie size [bytes]bytes/nodeallocated [bytes]wasted [bytes]wasted [%]
english12232,249,620742.36235,286,1763,036,5561.29
german12495,588,296811.81501,844,7446,256,4481.25
french12894,746,784689.82906,803,72812,056,9441.33
polishn/an/an/an/an/an/a

Pointer to array of limited set of edges [version 1b]

Do not store the array of all possible pointers, but only a continuous range between first and last non-null pointer.

Node structure:

text
struct TrieNode {
        /* user data */

        uint8_t lo;
        uint8_t hi;
        struct TrieNode** children;
}

The array has size hi - lo + 1.

Next function:

text
TrieNode* NEXT(TrieNode* node, uint8_t letter) {
        if (node->children) {
                if (letter >= node->lo and letter <= node->hi)
                        return node->children[letter - node->lo];
                else
                        return NULL;
        }
        else
                return NULL;
}

Pros

  • much smaller memory (but still quite large and in degenerated cases allocated memory could be as large as in version 1a)

Cons

  • more tests in order to retrieve a child node
  • inserting/deleting nodes require more operations

Experiments results

languagenode size [bytes]trie size [bytes]bytes/nodeallocated [bytes]wasted [bytes]wasted [%]
english1612,688,51240.5617,552,0004,863,48827.71
german1618,303,58829.9828,461,20810,157,62035.69
french1644,657,33634.4363,965,32019,307,98430.19
polish16312,236,52452.62393,812,63281,576,10820.71

Pointer to array of limited set of edges — lookup tables

This method extends 1b approach. The size of chars set stored in entire trie may be smaller than 256, for example words in english dictionary contains small and big letters and apostrophe, i.e. about 53 chars. Thus the size of array in each node could be much smaller, with cost of additional translation table(s).

Such translation tables can be applied for all nodes or be specific for nodes at the same depth. Sample functions retrieving a child node:

text
TrieNode* NEXT(TrieNode* node, uint8_t letter) {
        const uint16_t L = trie->translate[letter];
        if (L == trie->INVALID_LETTER)
                return NULL;
        else
                return node->children[L]
}


TrieNode* NEXT(TrieNode* node, uint8_t letter) {
        /* depth could be parameter of function! */
        const size_t depth = get_depth(node);

        const uint16_t L = trie->translate[depth][letter];
        if (L == trie->INVALID_LETTER)
                return NULL;
        else
                return node->children[L]
}

Pros

  • even less memory (but still large)

Cons

  • 3 or 4 memory accesses, additional tests
  • translation tables can be constructed when a trie already exists
  • adding new words containing invalid characters forces to rebuild lookup tables

Experiments results

Global translation table has 54 elements, while size of translation tables created for each depth vary from 1 to 53:

Results for tries with additional lookups.

methodnode struct sizetotal sizebytes/node
All possible edges1036324,117,7801036.00
Global translation table1672,582,360232.00
Depth-local translation table1641,797,316133.60

Dynamic table of pointers [version 2]

2011-03-26-trie-representation/v2.pic.png

Dynamic table of pointers — store only non-null pointers. This require store also size of a table and a edge label.

text
struct TrieNode {
        /* user data */

        uint8_t letter; // edge label
        uint16_t n;             // array size
        TrieNode** children;    // array
}

Procedure returns next node:

text
TrieNode* g(TrieNode* node, uint8_t letter) {
        int i;
        const int n = node->n;
        for (i=0; i < n; i++)
                if (node->child[i]->letter == letter)
                        return node->child[i];

        return NULL;
}

Pros

  • Simple to use, less memory usage than the linked list version.

Cons

  • Linear time to obtain a child node.
  • Many indirect memory operations.
  • Adding/removing require reallocating memory, this brings internal fragmentation.

Improvements

  • Keep a table sorted and thus allow logarithmic time to obtain a child (binary search).
  • Or use move-to-front strategy.
  • For n = 1 do not allocate 1-element table, but save pointer directly in a node structure (version 2a).
text
struct TrieNode {
        /* user data */

        uint8_t letter;
        uint16_t n;
        union {
                TrieNode*       single_child;   // valid when n = 1
                TrieNode**      ptr_array;
        }
}

Experiments results

Version 2:

languagenode size [bytes]trie size [bytes]bytes/nodeallocated [bytes]wasted [bytes]wasted [%]
english166,257,09620.0011,193,3764,936,28044.10
german1612,209,39620.0022,448,21610,238,82045.61
french1625,941,59620.0045,420,39219,478,79642.89
polish16118,673,15620.00201,448,15282,774,99641.09

Version 2a:

languagenode size [bytes]trie size [bytes]bytes/nodeallocated [bytes]wasted [bytes]wasted [%]
english165,563,90417.788,419,6802,855,77633.92
german1610,607,98017.3816,040,8165,432,83633.87
french1623,480,02418.1035,573,00812,092,98433.99
polish16109,473,04818.45164,644,26455,171,21633.51

Linked list of pointers [version 2b]

2011-03-26-trie-representation/v2b.pic.png

Use single-linked list instead of dynamic table. This requires also store a letter (label's edge) on a list.

text
struct TrieNode {
        /* user data */

        ListItem* head;
};

ListItem {
        uint8_t         letter;
        TrieNode*       child;
        ListItem*       next;
};

Procedure returns next node:

text
TrieNode* g(TrieNode* node, uint8_t letter) {
        ListItem* item = node->head;

        while (item) {
                if (item->letter == letter)
                        return item->child;
                else
                        item = item->next;
        }

        return NULL
}

Pros

  • Store only required links.

Cons

  • Linear time to obtain a child node.
  • Many indirect memory operations.
  • Each node of linked list has small size (2 pointers = 8 bytes on 32-bit machine), thus large internal memory fragmentation when a standard C library routines are used (malloc/free).

Improvements

  • Use move-to-front strategy, i.e. move last found item to the front of a list — next search will find this item faster.
  • Use memory pools to reduce memory wasting. See section Memory allocators

Experiments results

languagenode size [bytes]trie size [bytes]bytes/nodeallocated [bytes]wasted [bytes]wasted [%]
english127,508,50824.0010,011,3602,502,85225.00
german1214,651,26824.0019,535,0404,883,77225.00
french1231,129,90824.0041,506,56010,376,65225.00
polish12142,407,78024.00189,877,05647,469,27625.00

Dynamic table modifications

Table of letters and pointers [version 3]

2011-03-26-trie-representation/v3.pic.png

The dynamic table require two memory reads: the first gets a pointer to child, then get a letter from a child. In this representation letters are separated from the node structure and saved in front of the table of pointers. Sample memory layout for node with 3 children:

text
|     letters   |       pointers        |
+---+---+---+---+-------+-------+-------+
| a | b | c | _ | ptr_0 | ptr_1 | ptr_2 |
+---+---+---+---+-------+-------+-------+
  0   1   2   x     0       1       2     <- index

Letters area has size rounded to alignment, in this case 4 bytes.

Structure of node is simple:

text
struct TrieNode {
        /* user data */

        uint16_t n;
        void* children;
}

Procedure returns next node:

text
TrieNode* NEXT_v3(TrieNode* node, uint8_t letter) {
        const int n = node->n;
        const letters_size = round_up(n, aligment);

        char* letters =
                (char*)(node->children);

        TrieNode* pointers =
                (TrieNode*)(node->children + letters_size);

        /* find index */
        for (i=0; i < n; i++)
                if (chars[i] == letter)
                        return pointers[i];

        return NULL;
}

Pros

  • Letters are stored in a single memory area, thus specialized routines to locating chars could be used, for example functions that use SSE instructions.

Cons

  • Linear time to obtain a child node.
  • Adding/removing words require reallocating memory.
  • Internal memory fragmentation in letters area.
  • Because of structure packing size of node don't become smaller.

Improvements

  • Keep a table sorted and thus allow logarithmic time to obtain child nodes.
  • Or use move-to-front strategy.
  • After all structure packing could be ally. If alignment is 4 bytes, then there are two free bytes after n element. If n == 1 or n == 2 we don't need to allocate letters part of dynamic table, but use these spare bytes. (version 3a)
text
struct TrieNode {
        /* user data */

        uint16_t n;
        uint8_t  byte0; // n == 1 or n == 2
        uint8_t  byte1; // n == 2
        void*    children;
}

Procedure returns next node:

text
TrieNode* NEXT(TrieNode* node, uint8_t letter) {
        const int n = node->n;
        switch (n) {
                case 0:
                        return NULL;

                case 1:
                        if (node->byte0 == letter)
                                return (TrieNode**)(node->children)[0];
                        else
                                return NULL;

                case 2:
                        if (node->byte0 == letter)
                                return (TrieNode**)(node->children)[0];
                        else if (node->byte1 == letter)
                                return (TrieNode**)(node->children)[1];
                        else
                                return NULL;

                default:
                        return NEXT_v3(node, letter);
        }
}

Experiments results

Version 3:

languagenode size [bytes]trie size [bytes]bytes/nodeallocated [bytes]wasted [bytes]wasted [%]
english167,588,47624.2611,349,1603,760,68433.14
german1618,070,71624.1728,197,54410,126,82835.91
french1662,388,76024.2097,167,83234,779,07235.79
polish16310,656,95624.24480,136,984169,480,02835.30

Version 3a:

languagenode size [bytes]trie size [bytes]bytes/nodeallocated [bytes]wasted [bytes]wasted [%]
english166,406,06020.4811,349,1604,943,10043.55
german1615,098,29620.1928,122,60013,024,30446.31
french1652,107,67620.2196,885,33644,777,66046.22
polish16259,933,36420.28478,677,552218,744,18845.70

Table of letters, children count and pointers [version 3b]

2011-03-26-trie-representation/v3b.pic.png

A modification of the previous scheme — move counter n to a dynamic array. Also type of n could be change to uint8_t. If node has no children, then pointer is NULL, and n never get value 0, so we have values outside range 1..256.

Structure of node is simple:

text
struct TrieNode {
        /* user data */

        void* children;
}

Procedure returns next node:

text
TrieNode* NEXT(TrieNode* node, uint8_t letter) {
        const int n = (uint_8)(node->children[0]);
        const letters_size = round_up(n, aligment);

        char* letters =
                (char*)(node->children + 1);

        TrieNode* pointers =
                (TrieNode*)(node->children + letters_size + 1);

        /* find index */
        for (i=0; i < n; i++)
                if (chars[i] == letter)
                        return pointers[i];

        return NULL;
}

Sample memory layout for node with 3 children:

text
| n |  letters  |       pointers        |
+---+---+---+---+-------+-------+-------+
| 3 | a | b | c | ptr_0 | ptr_1 | ptr_2 |
+---+---+---+---+-------+-------+-------+
      0   1   2     0       1       2     <- index

Pros

  • smaller size of a node

Cons

see previous section

Experiments results

languagenode size [bytes]trie size [bytes]bytes/nodeallocated [bytes]wasted [bytes]wasted [%]
english126,297,67620.138,841,4242,543,74828.77
german1212,267,36020.0917,782,6645,515,30431.02
french1226,152,13220.1635,824,8969,672,76427.00
polish12120,114,86420.24158,666,64838,551,78424.30

Array of children nodes [version 4]

2011-03-26-trie-representation/v4.pic.png

Instead of storing pointers to children it's possible to store all children nodes in a single array and save only one pointer to that array.

Structure of node:

text
struct TrieNode {
        /* user data */

        uint16_t  n
        uint8_t   letter;
        TrieNode* array;
}

Pros

  • much smaller memory requirements
  • memory locality (spatial locality)

Cons

  • adding/removing nodes require reallocation, this bring internal memory fragmentation

Size improvements

If a trie is not modified, then memory could be even more compacted, but following constraints are set:

  • all nodes are stored in a continuous area of memory (array)
  • there are up to 223 − 1 nodes

Structure of node:

text
struct TrieNode {
        /* user data */

        uint32_t        letter:8;       // 8-bit for letter
        uint32_t        eol:1;          // 1-bit for End-of-list marker
        uint32_t        index:23;       // index of subarray of children
}

Procedure that returns child node:

text
TrieNode nodes[k];

TrieNode* NEXT(TrieNode* node, const uint8_t letter) {
        if (node->index == 0)
                return NULL;

        TrieNode* children = &nodes[index];
        size_t i = 0;

        while (1) {
                if (children[i].letter == letter)
                        return &children[i];
                else {
                        if (children[i].eol)
                                // last element of array
                                return NULL;
                        else
                                i += 1;
                }
        }
}

Such trie takes exactly nodes count * sizeof(TrieNode).

Experiments results

languagenode size [bytes]trie size [bytes]bytes/nodeallocated [bytes]wasted [bytes]wasted [%]
english165,005,68016.006,814,9521,809,27226.55
german169,767,52016.0013,623,0803,855,56028.30
french1620,753,28016.0027,680,5366,927,25625.03
polish1694,938,52816.00122,940,56828,002,04022.78

Table of letter and array of children nodes [version 4a]

This is merge of version 4 and version 3b — children nodes are saved in an array (v4), a children counter and edge lables are also stored in the table (v3b).

Structure of node:

text
struct TrieNode {
        /* user data */

        uint8_t* array;
}

(Pseudo)structure od array:

text
pseudostruct array {
        uint8_t n;
        uint8_t letters[n];
        uint8_t __alignment__[?];

        TrieNode next[n];
}

Procedure returns next node:

text
TrieNode* NEXT(TrieNode* node, uint8_t letter) {
        const int n = (int)(node->array[0]);
        const letters_size = round_up(n + 1, aligment);

        char* letters =
                (char*)(node->array + 1);

        TrieNode* next =
                (TrieNode*)(node->array + letters_size);

        /* find index */
        for (i=0; i < n; i++)
                if (letters[i] == letter)
                        return &next[i];

        return NULL;
}

Pros & cons

same as for version 4

Experiments results

languagenode size [bytes]trie size [bytes]bytes/nodeallocated [bytes]wasted [bytes]wasted [%]
english124'687'40014.986'340'6241'653'22426.07
german129'290'88015.2212'901'6163'610'73628.00
french1219'209'80014.8125'460'4086'250'60825.55
polish1286'460'39214.57111'249'82424'789'43222.28

Experiments results summary

English words:

layoutnode size [bytes]trie size [bytes]bytes/nodeallocated [bytes]wasted [bytes]wasted [%]
version 11,032322,866,3601032.00325,369,2162,502,8560.77
version 1a12232,249,620742.36235,286,1763,036,5561.29
version 1b1612,688,51240.5617,552,0004,863,48827.71
version 2166,257,09620.0011,193,3764,936,28044.10
version 2a165,563,90417.788,419,6802,855,77633.92
version 2b127,508,50824.0010,011,3602,502,85225.00
version 3167,588,47624.2611,349,1603,760,68433.14
version 3a166,406,06020.4811,349,1604,943,10043.55
version 3b126,297,67620.138,841,4242,543,74828.77
version 4165,005,68016.006,814,9521,809,27226.55
version 4a124'687'40014.986'340'6241'653'22426.07

German words:

layoutnode size [bytes]trie size [bytes]bytes/nodeallocated [bytes]wasted [bytes]wasted [%]
version 11,032630,005,0401032.00634,888,8164,883,7760.77
version 1a12495,588,296811.81501,844,7446,256,4481.25
version 1b1618,303,58829.9828,461,20810,157,62035.69
version 21612,209,39620.0022,448,21610,238,82045.61
version 2a1610,607,98017.3816,040,8165,432,83633.87
version 2b1214,651,26824.0019,535,0404,883,77225.00
version 31618,070,71624.1728,197,54410,126,82835.91
version 3a1615,098,29620.1928,122,60013,024,30446.31
version 3b1212,267,36020.0917,782,6645,515,30431.02
version 4169,767,52016.0013,623,0803,855,56028.30
version 4a129'290'88015.2212'901'6163'610'73628.00

French words:

layoutnode size [bytes]trie size [bytes]bytes/nodeallocated [bytes]wasted [bytes]wasted [%]
version 11,0321,338,586,5601032.001,348,963,21610,376,6560.77
version 1a12894,746,784689.82906,803,72812,056,9441.33
version 1b1644,657,33634.4363,965,32019,307,98430.19
version 21625,941,59620.0045,420,39219,478,79642.89
version 2a1623,480,02418.1035,573,00812,092,98433.99
version 2b1231,129,90824.0041,506,56010,376,65225.00
version 31662,388,76024.2097,167,83234,779,07235.79
version 3a1652,107,67620.2196,885,33644,777,66046.22
version 3b1226,152,13220.1635,824,8969,672,76427.00
version 41620,753,28016.0027,680,5366,927,25625.03
version 4a1219'209'80014.8125'460'4086'250'60825.55

Polish words:

layoutnode size [bytes]trie size [bytes]bytes/nodeallocated [bytes]wasted [bytes]wasted [%]
version 1n/an/an/an/an/an/a
version 1an/an/an/an/an/an/a
version 1b16312,236,52452.62393,812,63281,576,10820.71
version 216118,673,15620.00201,448,15282,774,99641.09
version 2a16109,473,04818.45164,644,26455,171,21633.51
version 2b12142,407,78024.00189,877,05647,469,27625.00
version 316310,656,95624.24480,136,984169,480,02835.30
version 3a16259,933,36420.28478,677,552218,744,18845.70
version 3b12120,114,86420.24158,666,64838,551,78424.30
version 41694,938,52816.00122,940,56828,002,04022.78
version 4a1286'460'39214.57111'249'82424'789'43222.28

Speed

Procedure tests if word is present in trie:

text
bool exists(Trie* trie, char* string) {
        char* c = string;
        TrieNode* node = trie->root;
        while (*c and node)
                node = NEXT(node, *c++);

        return (node && node->end_of_word)
}

All representations has been tested using similar procedure, and there are two conclusion:

  • Any array-based approach is fast, no differences spotted, even if large input data and large tries were used.
  • Linked list is 80 (eighty) times slower then array-based representation.

Memory allocators

Experiments clearly shows that internal memory fragmentation is significant, at least when GNU libc is used. The answer to this problem are specialized allocators.

All representations require allocate (or free) single nodes, thus memory pools could be used. For example GNU libc provides obstacks, but such stack-based memory pool is quite simple to write.

Representations using dynamic arrays require more complex memory pool, thus I wrote simple bitmap-based allocator. There is a linked list of arenas:

text
typedef struct MemPool {
        MemPool*        next_arena;
        size_t          free_count;
        uint8_t         bitmap[MAX_SIZE/8];
} MemPool;

The size of allocated array isn't stored in arena structure, because it's already saved in nodes. Thanks to that memory required by allocator is much smaller, but API is slightly different and isn't safe:

text
void* mempool_alloc(MemPool** pool, size_t n);
void  mempool_free(MemPool* pool, size_t n);

Experiments

Two representations were tested with the English dictionary:

  • linked list — separate stack-based memory pools for nodes and for list elements (both served 1024 elements per arena);
  • dynamic array — stack-based memory pool for nodes (1024 elements per arena) and bitmap-based allocator for arrays elements (256 elements per arena).

Linked list

  • memory pool for nodes:
    • arenas: 306
    • memory allocated for user: 3'760'128 bytes (306 * 1024 * 12)
    • memory used: 3'754'260 bytes
    • memory consumed by allocator structures: 4'896 bytes (306 * 16)
  • memory pool for list elements:
    • arenas: 306
    • memory allocated for user: 3'760'128 bytes (306 * 1024 * 12)
    • memory used: 3'754'248 bytes
    • memory consumed by allocator structures: 4'896 bytes (306 * 16)
  • theoretical size of tree: 7'508'508 bytes
  • malloc used bytes: 7'534'960 bytes
  • wasted: 36'244 bytes, 0.48% (26'452 - malloc, 2 * 4'896 - pools)

Dynamic array

  • memory pool for nodes:
    • arenas: 306
    • memory allocated for user: 5'013'504 bytes (305 * 1024 * 16)
    • memory used by user: 5'005'680 bytes
    • memory consumed by allocator structures: 4'896 bytes (306 * 16)
  • memory pool for arrays:
    • arenas: 1224
    • memory allocated for user: 1'253'376 bytes (1224 * 256 * 4)
    • memory used by user: 1'251'416 bytes (312854 * 4)
    • memory consumed by allocator structures: 48'960 bytes (1224 * 40)
  • theoretical size of tree: 6'257'096 bytes
  • malloc used bytes: 6'332'992 bytes
  • wasted: 129'752 bytes, 2.05% (75'896 - malloc, 4'896 and 48'960 - pools)

Updates

2011-03-31 : new representation [v4a], info about speed

2011-03-30 : added 2 new representations [1a, 1b], reorganization of text

2011-03-28 : added experiments results for memory pools