Skip to content
ImagineWorld

Organizing Data

node_idnode-book_the-secret-life-of-programs_chapter-10-organizing-data
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num10
chapter_titleOrganizing Data
governed_byCORPUS
constitutional_citationCONSTITUTION
figure_reviewassets/slp-fig-10-01-logo-ly-ge.png, assets/slp-fig-10-02-diagram-showing-bitwidths-of-c-primitive-data.png, assets/slp-fig-10-03-c-string-storage-and-termination-array-with.png, assets/slp-fig-10-04-diagram-showing-a-structure-with-fields-hours.png, assets/slp-fig-10-05-structure-for-calendar-entry-showing-startend-eventname.png, assets/slp-fig-10-06-structure-for-date-and-time-with-padding.png, assets/slp-fig-10-07-figure-79-pixel-union-showing-pixel-with.png, assets/slp-fig-10-08-diagram-of-a-singly-linked-list-with.png, assets/slp-fig-10-09-diagram-of-a-singly-linked-list-in.png, assets/slp-fig-10-10-diagram-showing-singly-linked-list-insertion-with.png, assets/slp-fig-10-11-diagram-showing-singly-linked-list-deletion-with.png, assets/slp-fig-10-12-flowchart-for-singly-linked-list-deletion-using.png, assets/slp-fig-10-13-flowchart-for-singly-linked-list-deletion-using.png, assets/slp-fig-10-14-diagram-showing-singly-linked-list-deletion-in.png, assets/slp-fig-10-15-diagram-of-malloc-structure-for-heap-management.png, assets/slp-fig-10-16-diagram-of-a-list-node-with-next.png, assets/slp-fig-10-17-diagram-comparing-less-efficient-and-more-efficient.png, assets/slp-fig-10-18-diagram-of-a-doubly-linked-list-showing.png, assets/slp-fig-10-19-diagram-showing-doubly-linked-list-insertion-with.png, assets/slp-fig-10-20-diagram-showing-doubly-linked-list-deletion-with.png, assets/slp-fig-10-21-binary-tree-nodes-containing-numbers.png, assets/slp-fig-10-22-binary-tree-insertion-algorithm-flowchart.png, assets/slp-fig-10-23-binary-tree-diagram-with-root-8-left.png, assets/slp-fig-10-24-binary-tree-lookup-algorithm-flowchart.png, assets/slp-fig-10-25-poorly-balanced-binary-tree-with-nodes-4.png, assets/slp-fig-10-26-two-binary-tree-diagrams-unbalanced-left-and.png, assets/slp-fig-10-27-filesystem-data-structure-diagram-showing-inode-direct.png, assets/slp-fig-10-28-balanced-binary-tree-with-root-ken-children.png, assets/slp-fig-10-29-btree-diagram-with-root-az-children-am.png, assets/slp-fig-10-30-diagram-showing-multiple-indices-for-names-with.png, assets/slp-fig-10-31-flowchart-for-zeroing-a-block-of-memory.png, assets/slp-fig-10-32-flowchart-for-zeroing-a-block-of-memory.png, assets/slp-fig-10-33-flowchart-for-zeroing-memory-using-modified-duffs.png, assets/slp-fig-10-34-diagram-showing-a-vector-of-size-pointers.png, assets/slp-fig-10-35-diagram-of-a-c-structure-for-an.png, assets/slp-fig-10-36-diagram-showing-object-structure-with-self-parent.png, assets/slp-fig-10-37-diagram-showing-search-key-hash-function-index.png, assets/slp-fig-10-38-hash-collision-diagram-showing-four-buckets-with.png, assets/slp-fig-10-39-hash-table-with-buckets-010-buckets-3.png, assets/slp-fig-10-40-database-sharding-diagram-showing-storage-processor-controller.png
reviewunbalanced $ inline delimiters
local graph

If you’ve been paying attention, you may have noticed a bit of an obsession when it comes to dealing with memory. Back in Chapter 3, you learned that the order in which memory devices such as DRAM, flash memory, and disk drives are accessed affects their speed. And in Chapter 5, you learned that performance also depends on whether or not the data that you need is present in cache memory. Keeping these characteristics of the memory system in mind when organizing your data leads to better performance. To help you do this, in this chapter we’ll examine a number of data structures, or standard ways of organizing data. Many of these exist to support the efficient use of different types of memory. This often involves a space/time trade-off wherein more memory is used to make certain operations faster. (Note that higher-level data structures are provided by programming languages, not the computer hardware itself.)

[!visual-conversion] logo “LY GE” Cropped from the scan (PDF page 223, printed p. 183): logo “LY GE”

The phrase locality of reference sums up much of what this chapter covers in a fully buzzword-compliant manner. Or “keep the data you need close, the data you’ll need soon even closer.”

Programming languages offer a variety of primitive data types. There are two aspects to these types: their size (number of bits) and their interpretation (signed, unsigned, floating point, char, pointer, Boolean). Figure 7-1 shows the data types available to programmers on a typical modern machine via the C programming language. Different implementations of C on the same machine, as well as different languages such as Pascal or Java, may present these data types differently. Some language environments include facilities that allow the programmer to query the endianness (see Figure 4-4 on page 96), number of bits per byte, and more.

char short long
7 0 15 0 31 0
long long
63 0
unsigned char unsigned short unsigned long
7 0 15 0 31 0
unsigned long long
63 0
float
31 0
double
63 0
int
31 0
unsigned int
31 0
pointer (assumes 64-bit machine)
63 0

Figure 7-1: Typical C language primitive data types

We saw all of these in Chapter 1 except the pointer; the only difference here is that we’re using the C language names for them.

American engineer Harold Lawson invented the pointer for the PL/I (Programming Language One) in 1964. A pointer is just an unsigned

[!visual-conversion] Diagram showing bit-widths of C primitive data types: char, short, … Cropped from the scan (PDF page 224, printed p. 184): Diagram showing bit-widths of C primitive data types: char, short, long, etc.

integer of some architecture-dependent size, but it’s interpreted as a memory address. It’s like the address of your house—it’s not the house itself, but it can be used to find your house. We’ve seen how this works before; it’s indirect addressing from “Addressing Modes” on page 104. A zero-valued, or NULL, pointer is not generally considered a valid memory address.

C popularized pointers. Some languages have implemented more abstract references in order to try to avoid problems resulting from sloppy pointer use, a subject I’ll touch on this later in the chapter. Pointers tend to be the size of the natural word on a machine so that they can be accessed in a single cycle.

Advances in chip technology spurred the development of a large number of new machines in the 1980s, which included the transition from 16-bit to 32-bit computers. A lot of code written in the 1970s and early 1980s was very cavalier about pointer use; for example, it assumed that pointers and integers were the same size and used them interchangeably. This code broke in often difficult-to-debug ways when ported to these new machines, spawning two independent remediation approaches. First, people started paying a lot more attention to portability issues. This solution was quite successful; portability and pointer issues are much less of a problem today. Second, languages that eliminated pointers were developed, such as Java. This approach has helped in some places but is not always worth the price.

The data types you saw in the previous section are simple; you can think of them as houses. Languages also support arrays, which can instead be likened to apartment buildings. Apartment buildings have an address, and the individual apartments have unit numbers. Programmers call the unit number the index (starting at 0, unlike most apartments), and the individual apartments are called array elements. Typical computer building codes mandate that all apartments in a building be identical. Figure 7-2 shows a building that contains ten 16-bit apartments in C.

Array → 0 1 element₀
2 3 element₁
4 5 element₂
6 7 element₃
8 9 element₄
10 11 element₅
12 13 element₆
14 15 element₇
16 17 element₈
18 19 element₉

Figure 7-2: Ten-element array of 16-bit numbers

Each box in Figure 7-2 is a byte. In this array of 16-bit items, therefore, each element occupies two 8-bit bytes. The element subscript indicates the array’s index.

An alternative way to view an array is the through the lens of relative addressing (see “Relative Addressing” on page 128). Each element is an offset from the address of the 0th element, or base address. Thus, element1_1 is 2 bytes away from element0_0.

The array in Figure 7-2 is a one-dimensional array—an ugly one-story building with all the apartments on one hall. Programming languages also support multidimensional arrays—for example, a building with four floors of three byte-sized apartments. This would be a two-dimensional array with two indices, one for the floor number and another for the apartment number on that floor. We can even make three-dimensional buildings with indices for wing, floor, and apartment; four-dimensional buildings with four indices; and so on.

It’s important to know how multidimensional arrays are laid out in memory. Let’s say we’re putting a flyer under every door in a 4×3 apartment building. We could do that in one of two ways. We could start on floor 0 and put a flier in apartment 0, then go to floor 1 and put a flier into apartment 0, and so on. Or we could start on floor 0 and put a flier under every door on that floor, then do the same on floor 1, and so on. This is a locality of reference issue. The second approach (doing all the doors on one floor) has better locality of reference and is much easier on the legs. You can see this in Figure 7-3, where the numbers in parentheses are the addresses relative to the start of the array.

Array

element$_0$ element$_{0,0}$ (0) element$_{0,1}$ (1) element$_{0,2}$ (2)
element$_1$ element$_{1,0}$ (3) element$_{1,1}$ (4) element$_{1,2}$ (5)
element$_2$ element$_{2,0}$ (6) element$_{2,1}$ (7) element$_{2,2}$ (8)
element$_3$ element$_{3,0}$ (9) element$_{3,1}$ (10) element$_{3,2}$ (11)

Figure 7-3: Two-dimensional array layout

The column index moves between adjacent columns, whereas the row index moves between rows, which are farther apart in the address space.

This approach extends to higher dimensions. If we had a five-building complex with four floors of three apartments per floor, Figure 7-3 would be replicated five times, once for each building. In address space, adjacent buildings are farther apart than adjacent rows, which are farther apart than adjacent columns.

Going back to Figure 7-2, think about what would happen if you tried to access element10_{10}. Some programming languages, such as Pascal, check to make sure that array indices are within the bounds of the array, but many others (including C) don’t. Without being checked, element10_{10} would land us at bytes 20 and 21 relative to the start of the array. That could crash a program if there’s no memory at that address, or it could be a security hole

allowing unintended access to data stored past the end of the array. It’s your job as a programmer to stay within bounds if the language doesn’t do it for you.

You’ve seen how you can construct arrays out of the primitive data types, but sometimes there isn’t a primitive data type that’s small enough for your purposes. For example, say Santa needs to track naughty versus nice for a large number of innocent children. Two values means that we need only 1 bit per child. We could easily use a byte for each value, but that’s less efficient—which translates into more warming at the North Pole and bad news for Frosty the Snowman because meltiness is considered a preexisting condition and not covered. What we really need is an array of bits, or a bitmap.

Bitmaps are easy to create. For example, say we want to keep track of 35 bits. We know that an array of five 8-bit bytes would be enough memory, as shown in Figure 7-4.

bits0 7 6 5 4 3 2 1 0
bits1 15 14 13 12 11 10 9 8
bits2 23 22 21 20 19 18 17 16
bits3 31 30 29 28 27 26 25 24
bits4 34 33 32

Figure 7-4: Array as bitmap

There are four basic operations that we can do on bitmaps: set a bit, clear a bit (set it to 0), test a bit to see if it is set, and test a bit to see if it is clear.

We can use integer division to find the byte containing a particular bit; all we have to do is divide by 8. We can do that quickly on machines with barrel shifters (see “Shiftiness” on page 99) by right-shifting the desired bit number by 3. For example, bit number 17 would be in the third byte because 17÷817 \div 8 is 2 in integer division, and byte 2 is the third byte counting from 0.

The next step is to make a mask for the bit position. Similar to its physical counterpart, a mask is a bit pattern with holes that we can “see through.” We start by ANDing our desired bit number with a mask of 0x07 to get the lower three bits; for 17, that’s 00010001 AND 00000111, which yields 00000001, or bit position 1. We then left-shift a 1 by that amount, giving us a mask of 00000010, which is the position of bit 17 in byte 2.

Using the array index and bit mask, we can easily perform the following operations:

Operation Formula
Set a bit $\text{bits}_{\text{index}} = \text{bits}_{\text{index}} \text{ OR mask}$
Clear a bit $\text{bits}_{\text{index}} = \text{bits}_{\text{index}} \text{ AND (NOT mask)}$
Test for set bit $(\text{bits}_{\text{index}} \text{ AND mask}) \neq 0$
Test for clear bit $(\text{bits}_{\text{index}} \text{ AND mask}) = 0$

There’s another useful application of bitmaps: to indicate whether resources are available or busy. If a set bit represents a busy resource, we can scan the array looking for a byte that’s not all 1s. This lets us test eight at a time. Of course, we would need to find the clear bit once we find a byte that contains one, but that’s much more efficient than testing each bit individually. Note that in cases like this, it’s more efficient to use an array of the largest primitive data type, such as C’s unsigned long long, instead of an array of bytes.

You learned about encoding characters in “Representing Text” on page 22. A sequence of characters, such as those in this sentence, is called a string.

As with arrays, we often need to know a string’s length in order to be able to operate on it. Usually, it’s not enough to just make an array for each string, because many programs operate on variable-length string data; large arrays are often used when the length of a string isn’t known in advance. Since the array size is unrelated to the string length, we need some other method to track the string length. The most convenient way to do that is to somehow bundle the string length in with the string data.

One approach is to store the length in the string itself—for example, in the first byte. This works well but limits the length of the string to a maximum of 255 characters, which is insufficient for many applications. More bytes can be used to support longer strings, but at some point, the amount of overhead (bookkeeping bytes) exceeds the length of many strings. Also, because strings are bytes, they can have any alignment, but if multibyte counts are needed, strings would have to be aligned on those boundaries.

C uses a different approach, borrowed from the PDP-11 assembly language’s .ASCII pseudo-instruction, which doesn’t have a special data type for strings like some languages do. It just uses one-dimensional arrays of bytes; the fact that strings are arrays of characters is why the byte-sized data type in C is a char. But there’s a twist: C doesn’t store a string length. Instead, it adds an extra byte at the end of the array of characters for a NUL terminator. C uses the ASCII NUL character (refer back to Table 1-11), which has a value of 0, as a string terminator. In other words, the NUL terminator is used to mark the end of a string. This works both for ASCII and UTF-8, and it looks like Figure 7-5.

0 1 2 3 4 5 6
C h e e s e NUL

Figure 7-5: C string storage and termination

As you can see, C uses 7 bytes of memory for the string, even though it’s only six characters long, because an extra byte is needed for the terminator.

[!visual-conversion] C string storage and termination: array with indices 0-6 showing … Cropped from the scan (PDF page 228, printed p. 188): C string storage and termination: array with indices 0-6 showing characters C, h, e, e, s, e, NUL

NUL turns out to be a good choice for the terminator because most machines include an instruction that tests whether or not a value is 0. Any other choice would involve extra instructions to load the value against which we’d be testing.

The use of a string terminator instead of an explicit length has its benefits and drawbacks. On one hand, storage is compact, which is important, and there’s essentially no overhead to do something like “print each character in the string until the end is reached.” But when you need the string’s length, you have to scan the string for the end, counting the characters. Also, with this approach you can’t have a NUL character in a string.

Although simple rooms are good for some things, the market often demands fancier accommodations, such as suites. Most modern languages include facilities that allow you to roll your own data types—the “suites,” often called structures. The various rooms in each suite are its members.

Let’s say we’re writing a calendar program that includes a list (array) of events with their starting and ending dates and times. If we were doing this in C, the day, month, hours, minutes, and seconds would each be held in an unsigned char, but the year would need to be in an unsigned short. Figure 7-6 creates a structure for the date and time.

hours minutes seconds year month day

Figure 7-6: Structure for date and time

Note that this isn’t strictly necessary; we could just have arrays of hours, minutes, and so on. But it’s certainly more convenient to have an array of date-time structures, and it makes programs easier to read and understand. British computer scientist Peter Landin coined the term syntactic sugar in 1964 for constructs such as this that make programs “sweeter.” Of course, one person’s sweetener is often another person’s essential functionality, leading to intense philosophical debates. Many would argue that syntactic sugar is limited to things like replacing a = a + 1 with a += 1 or a++, while fewer would claim that arrays of structures are syntactic sugar for sets of arrays. Time further complicates this fuzzy definition: a += 1 and a++ were not syntactic sugar when they were introduced, as compilers weren’t as good and these constructs generated better machine language. On the other hand, structures were more sugary when they were introduced, because prior code used arrays; they’re more essential now that programs are designed with structures in mind.

We can use compound data types, such as our date-time structure, as if they’re primitive data types. Figure 7-7 combines a pair of date-time structures with a small array to hold an event name string to make a complete calendar event structure.

[!visual-conversion] Diagram showing a structure with fields: hours, minutes, seconds, year, … Cropped from the scan (PDF page 229, printed p. 189): Diagram showing a structure with fields: hours, minutes, seconds, year, month, day.

start hours minutes seconds year month day
end hours minutes seconds year month day
event_name Array of characters (string)

Figure 7-7: Structure for calendar entry

Structures often take up more memory space than you might expect. I discussed aligned and nonaligned memory in “Memory” on page 94. Say we built our date-time structure in an area zoned for 32-bit computers, as in Figure 4-2 on page 95. The language keeps the structure members in the order specified by the programmer because it might matter. But the language also has to respect the alignment (Figure 4-3 on page 95), which means that it can’t put the year in the fourth and fifth bytes, as shown in Figure 7-7, because that crosses a boundary. The language tools solve this problem by automatically adding padding as needed. The actual memory layout of our structure would look like Figure 7-8.

hours minutes seconds padding year month day

Figure 7-8: Structure for date and time with padding

You could rearrange the structure members to make sure that you ended up with a 7-byte structure with no padding. Of course, when you combine a pair of these into the calendar structure, the language tools will likely pad them out to 8 bytes anyway.

It’s worth mentioning that this is a contrived example and you shouldn’t necessary handle dates and times this way. The standard in many systems, which came from UNIX, is to use a 32-bit number to represent the number of seconds since the “UNIX epoch” began on January 1, 1970. This scheme will run out of bits in 2038, but many systems have expanded this to 64 bits in preparation.

Figure 1-21 showed a way to use four 8-bit values to represent color with transparency. That’s a great use for a structure, but it’s not always the best way to view that data. For example, if we needed to copy a color, it would be much more efficient to copy all 32 bits at once rather than doing four 8-bit copies. Another compound data type to the rescue.

Not only can we have suites, as we saw in the previous section, but we can also have offices with movable partitions, which are called unions in C. A union allows multiple views of the same space or content. The difference between a structure and a union is that everything in a structure takes memory, whereas everything in a union shares memory. Figure 7-9 combines the RGBA structure with an unsigned long to form a union.

pixel
components.red components.green components.blue components.alpha
color

Figure 7-9: Pixel union

[!visual-conversion] Structure for calendar entry showing start/end event_name with hours, minutes, … Cropped from the scan (PDF page 230, printed p. 190): Structure for calendar entry showing start/end event_name with hours, minutes, seconds, year, month, day fields and an array of characters (string) below.

[!visual-conversion] Structure for date and time with padding: hours, minutes, seconds, … Cropped from the scan (PDF page 230, printed p. 190): Structure for date and time with padding: hours, minutes, seconds, padding, year, month, day

[!visual-conversion] Figure 7-9: Pixel union showing pixel with components.red, components.green, components.blue, … Cropped from the scan (PDF page 230, printed p. 190): Figure 7-9: Pixel union showing pixel with components.red, components.green, components.blue, components.alpha under color

Using the union and C language syntax, we could set the pixel.color to 0x12345678 and then pixel.components.red would be 0x12, pixel.components.green would be 0x34, and so on.

Arrays are the most efficient way to keep lists of things. They only hold actual data, without requiring any additional bookkeeping information. But they don’t work as well for arbitrary amounts of data, because if we didn’t make the array large enough, then we have to create a new, larger array and copy all the data into it. And they waste space if we make them larger than necessary. Similarly, copying is required if you need to insert an element into the middle of a list or delete an element.

Linked lists can perform better than arrays when you don’t know in advance how many things you’ll be tracking. Singly linked lists, implemented using structures, look like Figure 7-10.

Figure 7-10: Singly linked list

Note that next is a pointer that holds the address of the next element in the list. The first thing in the list is known as the head; the last thing is the tail. We can recognize the tail because next is a value that can’t be another list element, usually a NULL pointer.

A big difference between the list shown in Figure 7-10 and an array is that all array elements are contiguous in memory. List elements can be anywhere in memory and look more like Figure 7-11.

Figure 7-11: Singly linked list in memory

Adding an element to a list is easy; just pop it on the head, as shown in Figure 7-12.

[!visual-conversion] Diagram of a singly linked list with head pointer, nodes … Cropped from the scan (PDF page 231, printed p. 191): Diagram of a singly linked list with head pointer, nodes containing ‘next’ and ‘data’, and a NULL terminator.

[!visual-conversion] Diagram of a singly linked list in memory with head … Cropped from the scan (PDF page 231, printed p. 191): Diagram of a singly linked list in memory with head pointer and next/data nodes.

Insert

[!visual-conversion] Diagram showing singly linked list insertion with nodes labeled ‘next’ … Cropped from the scan (PDF page 232, printed p. 192): Diagram showing singly linked list insertion with nodes labeled ‘next’ and ‘data’, and arrows indicating pointer updates.

Figure 7-12: Singly linked list insertion

Deleting an element is a bit more complicated because we need to make the next of the previous element point to the following element, as shown in Figure 7-13.

Delete

[!visual-conversion] Diagram showing singly linked list deletion with nodes and pointer … Cropped from the scan (PDF page 232, printed p. 192): Diagram showing singly linked list deletion with nodes and pointer updates.

Figure 7-13: Singly linked list deletion

One way to do that is by using a pair of pointers, as shown in Figure 7-14.

[!visual-conversion] Flowchart for singly linked list deletion using a pair of … Cropped from the scan (PDF page 232, printed p. 192): Flowchart for singly linked list deletion using a pair of pointers

Figure 7-14: Singly linked list deletion using a pair of pointers

The current pointer walks the list looking for the node to delete. The previous pointer allows us to adjust the next of the node before the one to delete. We use a dot (.) to indicate a member of a structure, so current.next means the next member of the current node.

NOTE Figure 7-14 isn’t a great example; although to be fair, I looked online while writing this section and found algorithms that were much worse. The problem with the code shown here is that it’s complicated because a special test is needed for the list head.

The algorithm in Figure 7-15 shows how the power of double indirect addressing eliminates the special case, resulting in simpler code.

plaintext Start ↓ current ← Address of head ↓ Does memory addressed by current contain NULL? ├── Yes → Done ↓ No Does current contain address of node to delete? ├── Yes → Memory addressed by current ← node to delete.next → Done ↓ No current ← Address of current.next ↑ └───────────────────────────────────────┘

*Figure 7-15: Singly linked list deletion using indirect addressing*
Let’s examine how this algorithm works in more detail. Have a look at Figure 7-16. The subscripts show how current changes as the algorithm proceeds.
```plaintext
current₀ → head → A → B → C → D → E
↑ ↑ ↑ ↑ ↑
head A.next B.next C.next
↑ ↑ ↑ ↑
current₁ current₂ current₃ current₄

Figure 7-16: Singly linked list deletion in action

The steps shown in Figure 7-16 are complicated, so let’s walk through them.

  1. We start by setting current₀ to the address of head, which results in current₁, which in turn points to head. This means that current points to head, which points to list element A.

  2. We’re not looking for element A, so we move along.

[figure owed: ]

[!visual-conversion] Flowchart for singly linked list deletion using indirect addressing Cropped from the scan (PDF page 233, printed p. 193): Flowchart for singly linked list deletion using indirect addressing

[figure owed: ]

[!visual-conversion] Diagram showing singly linked list deletion in action with nodes … Cropped from the scan (PDF page 233, printed p. 193): Diagram showing singly linked list deletion in action with nodes head, A, B, C, D, E and current pointers current₀ to current₄.

  1. As shown by the dashed arrow, we set current to the address of the next pointer in the element pointed to by whatever current points to. Since current₁ points to head, which points to element A, current₂ ends up pointing to A.next.

  2. It’s still not the element that we want to delete, so we do it all again, causing current₃ to reference B.next.

  3. It’s still not the element that we want to delete, so we do it all again, causing current₄ to reference C.next.

  4. C.next points to element D, which is the one we want to delete. Following the light dashed arrow, we follow current to C.next to D, and replace C.next with the contents of D.next. Since D.next points to element E, C.next now points to E as shown by the heavy dashed arrow, removing D from the list.

We could modify the preceding algorithm to insert links into the middle of the list. That might be useful if we, for example, wanted the list to be ordered by date, name, or some other criteria.

Earlier I mentioned that this second algorithm produced better code. Let’s compare the two as written in the C programming language. You don’t have to understand this code to see the difference between Listing 7-1 and Listing 7-2.

struct node {
struct node *next;
// data
};
struct node *head;
struct node *node_to_delete;
struct node *current;
struct node *previous;
previous = (struct node *)0;
current = head;
while (current != (struct node *)0) {
if (current == node_to_delete) {
if (previous == (struct node *)0)
head = current->next;
else
previous->next = current->next;
break;
}
else {
previous = current;
current = current->next;
}
}

Listing 7-1: C language code for singly linked list deletion using a pair of pointers

struct node { struct node *next; // data };

struct node *head; struct node *node_to_delete; struct node **current;

for (current = &head; *current != (struct node *)0; current = &((*current)->next)) if (*current == node_to_delete) { *current = node_to_delete->next; break; } }

Listing 7-2: C language code for singly linked list deletion using double indirect addressing

As you can see, the indirect addressing version of this code in Listing 7-2 is much simpler than the code using a pair of pointers in Listing 7-1.

Our discussion of linked list insertion conveniently omitted something important. I showed how to insert a new node but didn’t say where the memory for that node came from.

We saw back in Figure 5-16 that program data space starts with a section for statically allocated data followed by the heap that the runtime library sets up for the program. This is all of the data memory available to a program (except for the stack and interrupt vectors) on machines that don’t have memory management units (MMUs). On systems with MMUs, the runtime library requests the amount of memory it thinks it needs, because tying up all of the main memory doesn’t make sense. The break is the end of the memory available to a program, and there are some system calls that grow or shrink the amount of available memory.

Memory for variables such as arrays is static; that is, it’s assigned an address that doesn’t change. Things like list nodes are dynamic; they come and go as needed. We get memory for them from the heap.

A program needs some way to manage the heap. It needs to know what memory is in use and what’s available. There are library functions for this so that you don’t have to write your own. In C, they’re the malloc and free functions. Let’s look at how they can be implemented.

One implementation of malloc works by using a singly linked list data structure. The heap is divided up into blocks, each of which has a size and a pointer to the next block, as shown in Figure 7-17.

[figure owed: ]

[!visual-conversion] Diagram of malloc structure for heap management showing three linked … Cropped from the scan (PDF page 236, printed p. 196): Diagram of malloc structure for heap management showing three linked blocks with next, size, and data fields.

Figure 7-17: malloc structure for heap management

Initially there’s just one block for the entire heap. When a program asks for memory, malloc looks for a block that has enough space, returns the caller a pointer to the requested space, and adjusts the size of the block to reflect the memory that it gave away. When a program frees memory using the free function, it just puts the block back in the list.

At various times, malloc scans the list for adjacent free blocks and coalesces them into a single larger block. One way of doing this is when allocating memory (calling malloc) because allocation requires going through the list looking for a large enough block. Over time, the memory space can become fragmented, which means there’s no available block of memory large enough to satisfy a request, even if not all memory has been used up. On systems with MMUs, the break is adjusted to get more memory if needed.

You can see that there’s a certain amount of overhead to this approach: next and size add 16 bytes to each block on a 64-bit machine.

Freeing unallocated memory is a common error that inexperienced programmers make. Another is continuing to use memory that has already been freed. As you can see in Figure 7-17, if you write data outside the bounds of allocated memory, you can corrupt the size and next fields. That’s particularly insidious because the problems this causes may not show up until a later operation needs to use the information in those fields.

One side effect of technological advances is that small machines often come with way more RAM than your program needs. In these cases, it’s better to just statically allocate everything because that reduces overhead and eliminates memory allocation bugs.

Linked lists that include text strings are common. Suppose we have a linked list where the node includes a pointer to a string, as shown in Figure 7-18.

[figure owed: ]

[!visual-conversion] Diagram of a list node with ‘next’ and ‘string’ fields, … Cropped from the scan (PDF page 236, printed p. 196): Diagram of a list node with ‘next’ and ‘string’ fields, pointing to a string ‘c a t NUL’.

Figure 7-18: List node with string

We have to allocate memory not only for each node but also for the string attached to the node. The malloc overhead can be significant, especially on a 64-bit machine where we would have 16 bytes of overhead for the 16-byte node, and then another 16 bytes of overhead for a string such as the 4-byte cat in Figure 7-18.

We can reduce the overhead by allocating the node and string at the same time. Instead of allocating the node and then the string, we can allocate space for the sum of the node and string sizes plus whatever padding might be necessary for alignment. This means that nodes are of variable size, which is okay. This trick cuts the overhead in half. The result looks like Figure 7-19, with a string of cat.

Less efficient More efficient
pointer pointer pointer
size size size
next c a t NUL next
string c a t NUL string

Figure 7-19: More efficient memory allocation

This approach is also more efficient when you are deleting nodes. In the less efficient case, two calls to free would be required, one for the string and another for the node. In the more efficient case, both get freed with a single call.

Two problems can arise from explicit dynamic memory management that are really problems of sloppy pointer use. Remember, a pointer is just a number that represents a memory address. But not all numbers are valid memory addresses. Using a pointer to try to access nonexistent memory or memory that doesn’t meet the processor alignment rules can cause an exception and crash a program.

You might be learning a programming language such as Java or JavaScript that doesn’t have pointers but supports dynamic memory allocation without equivalents to malloc and free. These languages instead implement garbage collection, a technique invented in 1959 by American computer and cognitive scientist John McCarthy (1927–2011) for the LISP programming language. Garbage collection has experienced a renaissance, partly as a prescriptive remedy for bad pointer use.

[figure owed: ]

[!visual-conversion] Diagram comparing less efficient and more efficient memory allocation for … Cropped from the scan (PDF page 237, printed p. 197): Diagram comparing less efficient and more efficient memory allocation for a node with string ‘cat’.

Languages like Java use references instead of pointers. References are an abstraction for pointers that provide much of the same functionality without actually exposing memory addresses.

Garbage-collected languages often have a new operator that creates items and allocates memory for them (this operator also appears in non-garbage-collected languages such as C++). There is no corresponding operator for item deletion. Instead, the language runtime environment tracks the use of variables and automatically deletes those it deems no longer in use. There are many ways in which this is done, one of which is to keep a count of references to variables so the variables can be deleted when there are no references left.

Garbage collection is a trade-off; it’s not without its issues. One issue is similar to the LSI-11 refresh problem (see “Random-Access Memory” on page 82) in that the programmer doesn’t have much control over the garbage collection system, which may decide to run even though the program needs to do something more important. Also, programs tend to take a lot of memory because it’s easy to leave unnecessary references around, which prevents memory from being reclaimed. This makes programs run slowly as opposed to just crashing due to bad pointers. It turns out that despite good intentions of solving the pointer problem, tracking down unnecessary references is actually harder to debug.

Our singly linked list delete function can be pretty slow because we have to find the element before the one we want to delete so that we can adjust its pointer. This could involve traversing a very long list. Fortunately, there’s a different type of list that solves this problem at the expense of some extra memory.

A doubly linked list includes a link not only to the next element but also to the previous element, as you can see in Figure 7-20. This doubles the per-node overhead, but it eliminates the need for list walking in the delete case, so it’s a space/time trade-off.

previous
next
data
previous
next
data
previous
next
data

Figure 7-20: Doubly linked list

The advantage of a doubly linked list is that you can insert and delete anywhere without having to spend time traversing the list. Figure 7-21 shows how you’d add a new node into a list after element A.

[figure owed: ]

[!visual-conversion] Diagram of a doubly linked list showing three nodes with … Cropped from the scan (PDF page 238, printed p. 198): Diagram of a doubly linked list showing three nodes with ‘previous’, ‘next’, and ‘data’ fields and bidirectional arrows.

So far, we’ve looked only at linear data structures. They’re great for many applications, but at some point their linearity can be a problem. That’s because storing data is only half of the work; we also need to be able to retrieve it efficiently. Let’s say we have a list of things stored in a linked list. We might need to walk the entire list to find a particular one; for a list of length nn , it could take nn lookups. This is fine for small numbers of things but impractical for large values of nn .

Earlier we saw how pointers could be used to connect nodes into linked lists. We’re not restricted to any number of pointers, so the ways in which we can organize data are limited only by our imagination and memory space. For example, we could come up with a hierarchical arrangement of nodes, as in the example back in Figure 5-4.

The simplest hierarchical data structure is the binary tree—“binary” not because of binary numbers but because a node can connect to two other nodes. Let’s make a node that contains a number arranged as shown in Figure 7-23.


Figure 7-21: Doubly linked list insertion

[figure owed: ]

[!visual-conversion] Diagram showing doubly linked list insertion with Element A and … Cropped from the scan (PDF page 239, printed p. 199): Diagram showing doubly linked list insertion with Element A and New node, with arrows indicating pointer updates.


Figure 7-22: Doubly linked list deletion

[figure owed: ]

[!visual-conversion] Diagram showing doubly linked list deletion with ‘Old’ node and … Cropped from the scan (PDF page 239, printed p. 199): Diagram showing doubly linked list deletion with ‘Old’ node and arrows marked with X indicating broken links.


As you can see, these operations on doubly linked list elements don’t require traversal.


Organizing Data Page 199

[figure owed: ]

[!visual-conversion] Binary tree nodes containing numbers Cropped from the scan (PDF page 240, printed p. 200): Binary tree nodes containing numbers

Figure 7-23: Binary tree nodes containing numbers

The root is the tree equivalent of a linked list’s head.

We’re going to hang out in a bingo parlor and record the numbers in a binary tree as they’re called out. We’ll then be able to look up numbers to see if they’ve been called. Figure 7-24 shows an algorithm that inserts a number into a tree. It works in a manner similar to our singly linked list deletion in that it relies on indirect addressing.

[figure owed: ]

[!visual-conversion] Binary tree insertion algorithm flowchart Cropped from the scan (PDF page 240, printed p. 200): Binary tree insertion algorithm flowchart

Figure 7-24: Binary tree insertion algorithm

Let’s look at this in action by inserting the numbers 8, 6, 9, 4, and 5. Nothing is attached to the root when we insert the 8, so we attach it there. When we insert the 6, the root spot is taken, so we compare that node; then because 6 is less than 8, we hit the left side. It’s vacant, so we plop a new node there. The 9 goes on the right-hand side of the 8, the 4 on the left-hand side of the 6, and so on, as shown in Figure 7-25.

[figure owed: ]

[!visual-conversion] Binary tree diagram with root 8, left child 6 (with … Cropped from the scan (PDF page 241, printed p. 201): Binary tree diagram with root 8, left child 6 (with children 4 and 5), right child 9.

You can see that even though there are five things in this data structure, worst case we can find one by checking three nodes. This beats a linked list, where we may have to check all five. It’s easy to look something up in a binary tree, as shown in Figure 7-26. Note that we don’t need a pointer to a pointer to a node here because we don’t have to modify the tree.

[figure owed: ]

[!visual-conversion] Binary tree look-up algorithm flowchart Cropped from the scan (PDF page 241, printed p. 201): Binary tree look-up algorithm flowchart

Figure 7-26: Binary tree look-up algorithm

You may have noticed that the arrangement of the tree depends on insertion order. Figure 7-27 shows what happens if we insert the numbers in order: 4, 5, 6, 8, and 9.

[figure owed: ]

[!visual-conversion] Poorly balanced binary tree with nodes 4, 5, 6, 8, … Cropped from the scan (PDF page 242, printed p. 202): Poorly balanced binary tree with nodes 4, 5, 6, 8, 9 inserted in order

This degenerate case looks a lot like a singly linked list. Not only do we lose the benefits of a binary tree, but now we have the additional overhead of the unused left pointers as well. We’d really prefer that our tree ended up looking like the one on the right in Figure 7-28.

[figure owed: ]

[!visual-conversion] Two binary tree diagrams: unbalanced (left) and balanced (right) Cropped from the scan (PDF page 242, printed p. 202): Two binary tree diagrams: unbalanced (left) and balanced (right)

Searching for something in a binary tree is a function of the depth in the tree; if it’s nn levels down, then it takes nn tests to find it. It takes only log⁡2n\log_2 n in a balanced binary tree as opposed to nn in a linked list. Putting that in perspective, in the worst case you’d have to visit 1,024 nodes in a linked list containing 1,024 nodes, but you’d need to visit only 10 nodes in a balanced binary tree.

There are numerous tree-balancing algorithms, which I’m not going to cover here in detail. It takes time to rebalance a tree, so there’s a trade-off between algorithm speed, insert/lookup time, and rebalancing time. Tree-balancing algorithms have more computational overhead, and some have

additional storage overhead. That overhead is quickly overcome, however, as the size of the tree increases, because log⁡2n\log_2 n becomes much smaller than nn .

We talked about disk drives back in “Block Devices” on page 85. Let’s look at them in more detail so we can understand their data organization peculiarities. Warning: we’re going to go pointer-crazy here!

I mentioned that the basic unit on a disk is a block and consecutive blocks are called clusters. It would be nice if we could just store data in clusters, which are contiguous sectors on a track. Although that’s done in certain circumstances where very high performance is required, it’s not a good general-purpose solution, and there might be more data than would fit on a track anyway. Instead, data is stored in whatever sectors are available; the operating system’s device driver provides the illusion of contiguous storage. Now we’re sort of in familiar territory, with a twist: instead of finding a block of storage to hold an object, we now have to find enough fixed-size blocks to hold an object and divide the object up among them.

Linked lists are not a great solution for keeping track of which disk blocks are free and which are in use, because traversing a list would be too slow. An 8 TiB disk has almost 2 billion blocks, and with worst-case behavior, 250 blocks can be accessed per second. That adds up to more than 15 years, which makes it impractical. That sounds really bad, but keep in mind that’s 1 MiB of data per second.

When we’re managing data in memory, it suffices to reference it using a pointer. But those are transient, and because disks are used for long-term data storage, we need something more persistent. You’ve already seen the answer: filenames. We need some way to both store those filenames on the disk and associate them with the blocks used to store the file data.

One way to manage all of this comes from—yup, you guessed it—UNIX. A number of blocks are set aside as inodes, a contraction of the disk block index and node; thus, inodes are index nodes. An inode contains various pieces of information about a file, such as its owner, size, and permissions. It also contains the indices of the blocks containing the file data, as you can see in Figure 7-29.

Figure 7-29: Filesystem data structure

[figure owed: ]

[!visual-conversion] Filesystem data structure diagram showing Inode, Direct blocks, Indirect blocks, … Cropped from the scan (PDF page 243, printed p. 203): Filesystem data structure diagram showing Inode, Direct blocks, Indirect blocks, Double indirect blocks, and Triple indirect blocks with arrows indicating relationships.

This looks really complicated, but it isn’t. An inode typically has 12 direct block pointers (they’re really not pointers, just block indices), which support files up to 4,096×12=49,1524,096 \times 12 = 49,152 bytes in length. That’s good enough for most files. If a file is larger, it uses indirect blocks. Assuming 32-bit indices (though these will need to be 64-bit soon), 1,024 indirect blocks which at 4 bytes each fit in one block, add another 4 MiB to the maximum file size. If that’s not enough, 4 GiB are available via the double indirect blocks, and finally another 4 PiB via the triple indirect blocks.

One piece of information an inode indicates is whether the blocks contain directory information instead of other data. A directory maps filenames to the inodes that reference the file data. One of the nice things about the way UNIX does things is that a directory is really just another type of file. That means a directory can reference other directories, which is what gives us our familiar tree-structured hierarchical filesystems.

At this point, you may be thinking that all this looks a lot like an arbitrary tree, which was true for a while. One of the features of this arrangement is that multiple inodes can reference the same blocks. Each reference is called a link. Links allow the same file to appear in multiple directories. It turns out that it’s very convenient to also be able to link to directories, so symbolic links were invented to make that possible. But symbolic links allow loops in the filesystem graph, so we need special code to detect that to prevent infinite looping. In any case, we have this complex structure that tracks the blocks used, but we’re still missing an efficient way to track the free space.

One way to accomplish this is by using a bitmap (see “Bitmaps” on page 187) with 1 bit for each disk block. A bitmap can be pretty large: an 8 TB disk drive would need almost 2 billion bits, which would consume about 256 MiB. It’s still a reasonable way to go—it’s way less than 0.01 percent of the total disk space, and it doesn’t all have to be in memory at the same time.

Working with bitmaps is pretty simple and efficient, especially if they’re stored in 64-bit words. Assuming that a 1 indicates a block in use and a 0 indicates a free block, we can easily look for words that are not all 1s to find free blocks.

But there is a problem with this approach: it’s possible for the filesystem graph and the free space bitmap to get out of sync. For example, the power could fail while data is being written to the disk. In the dark ages when computers had front panels with switches and blinking lights, you’d have to repair a damaged filesystem by inputting inode numbers through the front panel switches. This ordeal was remedied by programs such as fsck, which traverse the filesystem graph and compare it to the free block data. That’s a better approach, but it’s increasingly time-consuming as disks get larger. New journaling filesystem designs make damage control more efficient.

Binary trees are a great way to store data in memory, but they don’t work as well when it comes to storing huge amounts of data that doesn’t fit in memory. That’s partly because tree nodes tend to be small and therefore don’t map well to disk sectors.

A database is just a collection of data organized in some way. A database management system (DBMS) is a program that allows information to be stored in and retrieved from a database. A DBMS usually includes a number of interfaces layered on top of the underlying storage mechanism.

Databases are a common application of the B-tree data structure invented by German computer scientist Rudolf Bayer and American computer scientist Ed McCreight at Boeing in 1971. The B-tree is a balanced tree, but not a binary tree. It’s a bit less space efficient than a balanced binary tree but performs better, especially when data is stored on disk. This is yet another case where an understanding of memory architecture leads to more efficient code.

Say we have a balanced binary tree of names sorted alphabetically. It would look something like Figure 7-30.

[figure owed: ]

[!visual-conversion] Balanced binary tree with root Ken, children Dennis and Rob, … Cropped from the scan (PDF page 245, printed p. 205): Balanced binary tree with root Ken, children Dennis and Rob, and leaf nodes Brian, Doug, Mike, Steve.

A B-tree node has many more legs (children) than a binary tree node. The number of legs is chosen such that a node fits exactly into a disk block, as shown in Figure 7-31.

[figure owed: ]

[!visual-conversion] B-tree diagram with root A-Z, children A-M and N-Z, and … Cropped from the scan (PDF page 245, printed p. 205): B-tree diagram with root A-Z, children A-M and N-Z, and leaf nodes Brian, Dennis, Doug, Ken, Mike, Rob, Steve.

As you can see, the interior nodes are balanced, which yields a predictable search time. There are unused child links in Figure 7-31 that consume space. You can easily rebalance the tree when child links run out by changing the range covered by the node. For example, if the A-M node ran out of children, it could be subdivided into A-G and H-M nodes. This isn’t a great example, because power-of-2 subdivision is most often used but we don’t have an even number of things to subdivide here.

More keys per node means less fetching of nodes. The larger nodes aren’t a problem because they’re the size of a disk block, which is fetched as a unit. There is some wasted space because of unused child links, but it’s a reasonable trade-off.

Accessing sorted data is efficient, but we often need to access data sorted in more than one way. We might have both first and last names, or names and favorite bands.

Figure 7-31 shows nodes organized by name. These nodes are often referred to as the primary index. But we can have more than one index, as shown in Figure 7-32, which allows us to efficiently search for things in different ways.

Figure 7-32: Multiple indices

The trade-off with indices is that they need maintenance. Every index must be updated when the data changes. That’s a worthwhile cost when searching is a more common activity than modification.

I mentioned earlier that using arrays instead of linked lists requires copying data if the array needs to grow in size. You need copying in order to move page tables in and out of MMUs, free disk bitmaps on and off disk, and so on. Programs spend a lot of time moving data from one place to another, so it’s important to do it efficiently.

Let’s start with a half-measure: setting a block of length memory bytes to all 0s, as shown in Figure 7-33.

[figure owed: ]

[!visual-conversion] Diagram showing multiple indices for names, with first and last … Cropped from the scan (PDF page 246, printed p. 206): Diagram showing multiple indices for names, with first and last name indexes pointing to entries like Brian Kernighan, Dennis Ritchie, etc.

Start

current ← address of first byte to zero

length > 0? → No → Done

Yes

memory pointed to by current ← 0

current ← current + 1

length ← length - 1

Figure 7-33: Zeroing a block of memory

That algorithm works fine, but it’s not very efficient. Assuming that each box in Figure 7-33 takes the same amount of time to execute, we spend more time bookkeeping than zeroing memory locations. The loop unrolling technique can make this more efficient, as shown in Figure 7-34. For example, assuming that length is an even number, we can unroll the loop so that now more of the time is spent zeroing and less is spent on other things.

Start

current ← address of first byte to zero

length > 0? → No → Done

Yes

memory pointed to by current ← 0

current ← current + 1

memory pointed to by current ← 0

current ← current + 1

length ← length - 2

Figure 7-34: Zeroing a block of memory with loop unrolling

It would be nice to have a more general implementation, and fortunately there is one. When he worked at Lucasfilm, Canadian programmer

[figure owed: ]

[!visual-conversion] Flowchart for zeroing a block of memory Cropped from the scan (PDF page 247, printed p. 207): Flowchart for zeroing a block of memory

[figure owed: ]

[!visual-conversion] Flowchart for zeroing a block of memory with loop unrolling Cropped from the scan (PDF page 247, printed p. 207): Flowchart for zeroing a block of memory with loop unrolling

Tom Duff invented Duff’s Device to speed up the copying of data; Figure 7-35 shows a variant for zeroing memory. This approach works only if the length is greater than zero.

Start
↓
current ← address of first byte to zero
↓
eights ← ⌊length ÷ 8⌋
↓
length AND 0x7
↓
0? → Yes → memory pointed to by current ← 0
↓ No
7? → Yes → memory pointed to by current ← 0
↓ No
6? → Yes → memory pointed to by current ← 0
↓ No
5? → Yes → memory pointed to by current ← 0
↓ No
4? → Yes → memory pointed to by current ← 0
↓ No
3? → Yes → memory pointed to by current ← 0
↓ No
2? → Yes → memory pointed to by current ← 0
↓ No (1)
↓
memory pointed to by current ← 0
↓
current ← current + 1
↓
eights ← eights - 1
↓
eights > 0? → Yes → (loop back to "memory pointed to by current ← 0")
↓ No
Done

Figure 7-35: Zeroing a block of memory using a modified Duff’s Device

[figure owed: ]

[!visual-conversion] Flowchart for zeroing memory using modified Duff’s Device Cropped from the scan (PDF page 248, printed p. 208): Flowchart for zeroing memory using modified Duff’s Device

Duff’s Device unrolls the loop eight times and jumps into the middle to handle any leftover bytes. Though you might be tempted to unroll the loop further, this approach must be balanced with the code size because having it fit into the instruction cache is worth a lot of speed.

You can see on the loop side of the figure that the ratio of memory-zeroing time to bookkeeping time is much improved. Though the initial setup and branching to the proper place in the loop looks complicated, it really isn’t. It doesn’t take a pile of conditional branches, just some address manipulation as follows:

  1. Mask off all but the lower 3 bits of the length by ANDing with 0x7.
  2. Subtract the result from 8.
  3. Mask off all but the lower 3 bits by ANDing with 0x7.
  4. Multiply by the number of bytes between zeroing instructions.
  5. Add the address of the first zeroing instruction.
  6. Branch to that address.

Another way to increase the efficiency is to recognize that, for example, on a 64-bit machine, 8 bytes can be zeroed at a time. Of course, a bit of extra code is needed to handle leftover bytes at the beginning and the end. We need to use the algorithm from Figure 7-36 without the loop on the eights for the beginning and end. In the middle, we zero as many 8-byte chunks as possible.

This all becomes more complicated when we’re copying a block of data instead of just setting it to a value, because chances are, the source and destination won’t have the same byte alignment. It’s often worth testing for the case where both the source and destination are word aligned because it’s a pretty common case.

Copying has yet another complication, which is that it’s common to use copying to move data around in a region of memory. For example, we may have a buffer full of space-separated words in which we want to read the first word out of the buffer and then cram everything else down so that there’s room for more at the end. You have to take care when copying data in overlapping regions; sometimes you have to copy backward in order to avoid overwriting the data.

An interesting historical case was an early raster graphics terminal (see “Raster Graphics” on page 180) called the blit, designed by Canadian programmer Rob Pike at Bell Telephone Laboratories in the early 1980s, an era before it became practical to make custom integrated circuits to do this sort of thing. Source and destination data could overlap, such as in the case of dragging a window, and the data could be of any bit alignment. Performance was very important because processors weren’t very fast compared to today; the blit used a Motorola 68000. There was no MMU, so Pike wrote code that looked at the source and destination and generated optimal code on the fly to do the fastest copy. I did a similar implementation on a system that used the Motorola 68020. This achieved even better performance because the 68020 had an instruction cache into which the generated code

fit, so it didn’t have to keep accessing instruction memory. Note that this was a precursor to the JIT (just-in-time) techniques used in many virtual machines, including Java.

Copying data efficiently is important for system performance, but avoiding copying altogether helps even more. A lot of data is moved through the operating system to and from user space programs, and this data is often not in contiguous memory.

For example, say we’re generating some audio data in the mp3 format that we want to write to an audio device. Like many file formats, mp3 files consist of a number of frames, each of which includes a header followed by some data. A typical audio file contains multiple frames that, in many cases, have identical headers, as shown in Figure 7-36.

Header
CRC
Side information
Main data
Ancillary data

Figure 7-36: mp3 frame layout

We could build each frame by copying all the data into a buffer, but then when we write that data to an audio device, we’ll have to copy it yet again. Alternatively, we could write each portion of each frame separately, but that would increase the context-switching overhead and might cause problems for an audio device if only a partial frame gets written.

It would be more efficient if we could just hand the system a set of pointers to each piece of the frame and let the system gather the pieces together as they’re written, as shown in Figure 7-37. This is sufficiently worthwhile to justify system call (readv, writev) support.

VectorHeader
sizeCRC
sizeSide information
sizeMain data
sizeAncillary data

Figure 7-37: Data gather

The idea is to hand a vector of sizes and data pointers to the operating system, which then assembles them in order. There are versions for both

[figure owed: ]

[!visual-conversion] Diagram showing a vector of size pointers linked to Header, … Cropped from the scan (PDF page 250, printed p. 210): Diagram showing a vector of size pointers linked to Header, CRC, Side information, Main data, and Ancillary data blocks.

reading and writing: writing is known as gathering because data is collected from many places, while reading is known as scattering because data is dispersed to many places. The whole concept is called scatter/gather.

Scatter/gather became mainstream with the Berkeley networking code that became a foundation of the internet. I mentioned back in “TCP/IP” on page 158 that IP data is sent in packets and TCP is responsible for making sure that the packets arrive and are in the correct order. Packets arriving from a communications endpoint (well, it might be a communications endpoint to you, but it’s a socket to me) are gathered into a contiguous stream for presentation to user programs.

Since you’re learning to code, you may be learning an object-oriented language such as Java, C++, Python, or JavaScript. Object-oriented programming is a great methodology, but it can lead to performance issues if not used judiciously.

Object-oriented programming first gained serious traction with C++. C++ is an interesting case because it was initially built on top of C, which gives us an opportunity to see how it works.

Objects have methods, which are equivalent to functions, and properties, which are equivalent to data. Everything needed for an object can be collected into a single data structure. C’s support for type casting and pointers, especially pointers to functions, wins big here. A C structure for an object might look something like Figure 7-38.

Object
self
parent → Parent object
constructor → struct object *new() { . . . }
destructor → void gozer() { . . . }
method 1 → void method_1() { . . . }
method 2 → void method_2() { . . . }
method . . . →
property 1
property 2 → □□□□
property . . . →

Figure 7-38: A C structure for an object

Some properties, such as those with integer values (property 1), reside in the object structure itself, whereas others require additional memory allocation (property 2) that’s referenced by the object structure.

Clearly this structure could get quite large, especially if there are a lot of methods. We can address that by breaking the methods out into a separate structure—another space/time trade-off—as shown in Figure 7-39.

[figure owed: ]

[!visual-conversion] Diagram of a C structure for an object showing fields … Cropped from the scan (PDF page 251, printed p. 211): Diagram of a C structure for an object showing fields like self, parent, constructor, methods, and properties with pointers.

[figure owed: ]

[!visual-conversion] Diagram showing object structure with self, parent, methods, properties linked … Cropped from the scan (PDF page 252, printed p. 212): Diagram showing object structure with self, parent, methods, properties linked to a methods table with constructor, destructor, and method entries.

Figure 7-39: Separate method structure

Programmers used this sort of approach to object-oriented programming long before Danish programmer Bjarne Stroustrup invented C++. The original C++ was a wrapper around C that did things like this.

Why does this matter? Object-oriented ideologues believe that objects are the answer for everything. But as you can see in the previous figures, there’s a certain amount of overhead associated with objects. They have to carry around their own methods instead of using globally available functions. The upshot is that objects don’t pack as densely as pure data types, so stick to classic arrays when performance is paramount.

There are many reasons to sort data. Sometimes we just want sorted results, like when we alphabetize names to make them easier for people to find. Many times we want to store data in sorted form because it speeds up searching by reducing the number of memory accesses.

I’m not going to go into sorting algorithms in depth here, because it’s a pretty mature subject covered in many books. And plenty of good sort functions are available, so it’s not likely that you’ll need to write your own except as a homework problem. But there are a few important points to keep in mind.

One is that if the size of the things you’re sorting is larger than the size of a pointer, you should sort by rearranging the pointers to the data instead of by moving the data itself around.

Also, a convention for sorting has evolved. Our bingo parlor tree example enabled decisions based on an arithmetic comparison; we made decisions based on whether one number was less than, equal to, or greater than another. This method of decision making is rooted in the FORTRAN programming language from 1956, which included a statement that looked like Listing 7-3.

IF (expression) branch1, branch2, branch3

Listing 7-3: A FORTRAN arithmetic IF statement
<!-- page: 253 (printed 213) -->
This IF statement evaluated the expression and went to branch1 if the result was less than zero, branch2 if it was zero, and branch3 if it was greater than zero; the branches are similar to what we saw in “Branching” on page 105.
Sorting numbers is straightforward. It would be nice to apply this same methodology to sorting other things. We saw back in Figure 7-10 that a list node can include arbitrary data; the same is true with tree nodes and other data structures.
UNIX version III introduced a library function called qsort that implemented a variation of the classic quicksort algorithm. The interesting thing about the qsort implementation is that although it knew how to sort things, it didn’t know how to compare them. Therefore, it took advantage of C’s pointers to functions; when calling qsort with a list of things to sort, you also provided a comparison function that returned <0, 0, or >0 for less than, equal to, or greater than, just like the FORTRAN arithmetic IF. This approach allowed the caller to use qsort to sort things however they wanted. For example, if a node contained both a name and an age, the supplied function could compare first by age and then name so that qsort would produce results organized by age first and name second. This approach worked well and has been copied by many other systems.
The standard C library string comparison function strcmp was designed with this in mind; it returns a value of less than, equal to, or greater than zero. This has also become the de facto way of doing things.
The original ASCII version of strcmp just walked the strings, subtracting the character of one from the other. It kept going if the value was zero and returned 0 if the end of the strings was reached. Otherwise, it returned the subtraction result.
This is all well and good if you’re just sorting to distribute data in a tree, but it falls apart if you’re sorting to put things into alphabetical order. It worked in the ASCII days—you can see in Table 1-10 that the numerical order and alphabetical order are the same. Where it falls apart is with support for other locales. A side effect of support for other languages coming later is that only the ASCII characters are numerically in the correct collating order, or language-specific sorting rules.
For example, what value should be assigned to the German letter β, the sharp S (Eszett or scharfes S)? Its Unicode value is 0x00DF. Because of that, the word Straße would get sorted after the word Strasse using a vanilla string comparison. But these are actually different representations of the same word. The β is equivalent to ss. A string comparison that heeded the locale would say that the two words are equal.
# Making a Hash of Things
All the searching methods we’ve seen so far involve repeated testing while traversing a data structure. There’s another approach that performs better in some circumstances, called hashing. Hashing has many applications. We’re talking about in-memory storage and retrieval here, not mass storage. The general concept is to apply some hash function to the search keys that evenly splatter them onto the wall. If the hash function is easy to compute
<!-- page: 254 (printed 214) -->
and transforms a key into a splat in a unique location on the wall, then single-step lookup should be fast. Of course, there are some practical realities to consider.
Each splat represents the storage for the object associated with the key. The hash function must produce values that fit in memory. And it shouldn’t splatter things across too much memory or performance will suffer, both from using too much memory and from lack of locality of reference. Coming up with a perfect hash function isn’t really possible because we don’t have any prior knowledge of our keys.
One way to bound the storage is to have a hash function that maps keys into array indices. The array is called a *hash table*, shown in Figure 7-40. The array elements are called *buckets*.
Search key → Hash function → Index → Hash table
Figure 7-40: Hashing
What makes a good hash function? It needs to be easy to compute, and it needs to distribute keys evenly into the buckets. A simple hash function that works pretty well for text is just to sum up the character values. That’s not quite enough, because the sum might produce an index that’s beyond the end of the hash table, but we can easily solve this by making the index the sum modulo the hash table size. Let’s look at how this works in practice. We’ll use a table size of 11; prime numbers make good table sizes because multiples of the sum end up in different buckets, improving the splatter pattern.
Say we have an application that keeps track of songs played at our favorite jam band concerts. Maybe it stores the last played date. We’ll just use the first word of each song name.
As you can see in Figure 7-41, we start with *Hell* in a bucket—in this case, bucket 4. Next is *Touch* in bucket 9, followed by *Scarlet* in 3. But when we get to *Alligator*, we have a problem because the value of the hash function is the same as it was for *Scarlet*. This is called a *collision*.
1: Hell in a Bucket 2: Touch of Grey 3: Scarlet Begonias 4: Alligator
<table>
<tr>
<td>0</td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>1</td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>2</td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>3</td>
<td></td>
<td></td>
<td>Scarlet</td>
<td>Alligator</td>
</tr>
<tr>
<td>4</td>
<td>Hell</td>
<td>Hell</td>
<td>Hell</td>
<td>Hell</td>
</tr>
<tr>
<td>5</td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>6</td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>7</td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>8</td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>9</td>
<td></td>
<td>Touch</td>
<td>Touch</td>
<td>Touch</td>
</tr>
<tr>
<td>10</td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</table>
Figure 7-41: Hash collision
![](assets/slp-fig-10-37-diagram-showing-search-key-hash-function-index.png)
> [!visual-conversion] Diagram showing Search key → Hash function → Index → …
> Cropped from the scan (PDF page 254, printed p. 214): Diagram showing Search key → Hash function → Index → Hash table with empty buckets.
![](assets/slp-fig-10-38-hash-collision-diagram-showing-four-buckets-with.png)
> [!visual-conversion] Hash collision diagram showing four buckets with entries: Hell, Touch, …
> Cropped from the scan (PDF page 254, printed p. 214): Hash collision diagram showing four buckets with entries: Hell, Touch, Scarlet, Alligator.
<!-- page: 255 (printed 215) -->
We solve this by replacing the buckets with *hash chains*, which in their simplest form are singly linked lists, as shown in Figure 7-42.
Hash table
<table>
<tr><td>0</td><td>•</td></tr>
<tr><td>1</td><td>•</td></tr>
<tr><td>2</td><td>•</td></tr>
<tr><td>3</td><td>• → Alligator → Scarlet •</td></tr>
<tr><td>4</td><td>• → Hell •</td></tr>
<tr><td>5</td><td>•</td></tr>
<tr><td>6</td><td>•</td></tr>
<tr><td>7</td><td>•</td></tr>
<tr><td>8</td><td>•</td></tr>
<tr><td>9</td><td>• → Touch •</td></tr>
<tr><td>10</td><td>•</td></tr>
</table>
Figure 7-42: Hash chains
There are a number of trade-offs in hash chain management. We can just insert collisions at the head of the chain, as in Figure 7-42, because it’s fast. But lookup can slow down as the chains get longer, so we could also do an insertion sort, which takes longer but means we don’t have to traverse a chain to the end to determine whether or not an item exists. There are also many different collision-handling methods—for example, eliminating hash chains and using some algorithm to find an empty slot in the table.
It’s difficult to pick a good hash table size without knowing the expected number of symbols in advance. You can keep track of chain length and grow the hash table if the chains are getting too long. This can be an expensive operation, but it can pay off because it doesn’t need to be done very often.
There are many variations on hash functions. The holy grail of hash functions is the *perfect hash*, which maps each key to a unique bucket. It’s pretty much impossible to create a perfect hash function unless all of the keys are known in advance, but mathematicians have come up with much better functions than the one used in this example.
## Efficiency vs. Performance
A lot of effort has gone into making efficient search algorithms. Much of this work was done in an era when computers were expensive. Performance and efficiency were linked.
The cost of electronics has plunged so dramatically that it’s almost impossible to purchase anything that doesn’t include a gratuitous blue LED. Performance and efficiency are decoupled; there are cases where better performance can be achieved by using less efficient algorithms on more processors than more efficient algorithms on fewer processors.
![](assets/slp-fig-10-39-hash-table-with-buckets-010-buckets-3.png)
> [!visual-conversion] Hash table with buckets 0-10; buckets 3, 4, and 9 …
> Cropped from the scan (PDF page 255, printed p. 215): Hash table with buckets 0-10; buckets 3, 4, and 9 have linked lists: 3→Alligator→Scarlet, 4→Hell, 9→Touch.
<!-- page: 256 (printed 216) -->
One application of this decoupling is database *sharding*, also called *horizontal partitioning*. Sharding involves breaking up a database into multiple shards, each of which lives on its own machine, as shown in Figure 7-43.
![](assets/slp-fig-10-40-database-sharding-diagram-showing-storage-processor-controller.png)
> [!visual-conversion] Database sharding diagram showing Storage, Processor, Controller, and Interface components.
> Cropped from the scan (PDF page 256, printed p. 216): Database sharding diagram showing Storage, Processor, Controller, and Interface components.
Database operations requested over the interface are sent to all of the shards, and the results are assembled by a controller. This technique improves performance because operations are split across multiple workers.
A variation on sharding is called *MapReduce*, which essentially allows you to provide code to the controller for assembly of the intermediate results. This makes it possible to do operations such as “count the number of students in all math classes” without having to first request a list of students and then count them.
Databases aren’t the only application of this multiple processor approach. A historically interesting use is the Electronic Frontier Foundation’s DES (Data Encryption Standard) cracker built in 1998; see the book *Cracking DES* (O’Reilly, 1998) for the full story. A machine was constructed that used 1,856 custom processor chips, each of which tried a range of keys on the encrypted data. Any “interesting” results were forwarded to a controller for further analysis. This machine could test 90 billion keys per second.
## Summary
This chapter introduced you to a number of ways in which data can be organized to take advantage of what you’ve learned so far about computer hardware. In the next chapter, you’ll see how your programs get converted into forms that computer hardware can understand.