man unix/awk-arrays
awk's associative arrays: hash tables since 1979
count[$1]++ is the line that makes awk worth learning. It counts anything, with no declaration and no size. So what is count? How does it grow when a file has a million distinct keys? And why does for (k in count) print keys in an order that looks random but never changes?
This article reads the awk that ships with macOS. awk --version prints awk version 20200816. That is Brian Kernighan’s awk, the “one true awk”, as Apple builds it in its awk project. The upstream repository has no tag for 20200816, and Apple’s tags awk-32 to awk-40 all carry that version string. I read awk-40, the newest. Its tran.c and run.c are identical to awk-35’s. Apple doesn’t say which tag macOS 27.2.1 was built from, so I checked the main claims against the installed binary with experiments, which ran on an Apple M2 Pro. The rest come from the awk-40 source.
What POSIX promises
The POSIX.1-2024 page for awk says arrays “shall initially be empty, and their sizes shall change dynamically. The subscripts, or element identifiers, are strings, providing a type of associative array capability.” for (variable in array) iterates “assigning each index of array to variable in an unspecified order”. Numbers used as subscripts become strings first. An integer converts as if by sprintf("%d"), anything else with CONVFMT, which defaults to %.6g.
Nothing about hashing, growth, or what “unspecified” means in practice. That is all in the implementation.
The structure
awk.h defines two types. Every variable, field and array element is a Cell. An array is an Array of chains of cells:
typedef struct Cell {
uschar ctype; /* OCELL, OBOOL, OJUMP, etc. */
uschar csub; /* CCON, CTEMP, CFLD, etc. */
char *nval; /* name, for variables only */
char *sval; /* string value */
Awkfloat fval; /* value as number */
int tval; /* type info: STR|NUM|ARR|FCN|FLD|CON|DONTFREE|CONVC|CONVO */
char *fmt; /* CONVFMT/OFMT value used to convert from number */
struct Cell *cnext; /* ptr to next if chained */
} Cell;
typedef struct Array { /* symbol table array */
int nelem; /* elements in table right now */
int size; /* size of tab */
Cell **tab; /* hash table pointers */
} Array;
Awkfloat is typedef double Awkfloat;. Each element keeps its key as a C string in nval, and its value as both a string and a double. An array element is the same kind of object as a global variable. The global variables live in the same kind of table, symtab.
Array { nelem = 4, size = 50, tab }
│
▼
tab[0] ──► Cell "2" ──► NULL
tab[1] ──► Cell "3" ──► NULL
...
tab[17] ──► Cell "10" ──► NULL
...
tab[49] ──► Cell "1" ──► NULL
Hashing and inserting
The hash function in tran.c is four lines:
int hash(const char *s, int n) /* form hash value for string s */
{
unsigned hashval;
for (hashval = 0; *s != '\0'; s++)
hashval = (*s + 31 * hashval);
return hashval % n;
}
Multiply by 31, add the next byte, and take the remainder by the table size. lookup hashes the key and walks that chain with strcmp. setsymtab calls lookup first and returns the existing cell if there is one. Otherwise it allocates a cell, increments nelem, and pushes the cell onto the front of its chain:
tp->nelem++;
if (tp->nelem > FULLTAB * tp->size)
rehash(tp);
h = hash(n, tp->size);
p->cnext = tp->tab[h];
tp->tab[h] = p;
Growing
A new array starts with makesymtab(NSYMTAB), and NSYMTAB is 50. The two constants at the top of tran.c set the policy:
#define FULLTAB 2 /* rehash when table gets this x full */
#define GROWTAB 4 /* grow table by this factor */
So the table grows when it holds more than two elements per bucket on average, and it grows to four times its size. rehash allocates the new bucket array, moves every cell to its new chain, and frees the old array. The cells themselves are not copied. The sizes go 50, 200, 800, 3,200, 12,800, 51,200, 204,800, and the rehashes happen when the 101st, 401st, 1,601st, 6,401st and 25,601st element arrives. Between rehashes the load factor goes from 0.5 up to 2, which is high for a hash table. awk saves allocations and rehashes and pays with longer chains.
If the calloc in rehash fails, it just returns, and the table keeps its old size. The FIXES file has the entry for that change, dated 31 May 1992: “changed rehash so that if it runs out, it just returns; things will continue to run slow, but maybe a bit longer.”
Why for (k in a) comes out in that order
instat in run.c runs the loop. It walks the buckets from 0 to size - 1, and each chain from its head:
for (i = 0; i < tp->size; i++) { /* this routine knows too much */
for (cp = tp->tab[i]; cp != NULL; cp = ncp) {
setsval(vp, cp->nval);
ncp = cp->cnext;
x = execute(a[2]);
There is no random seed anywhere, so the order depends only on the keys, the order they arrived in, and the table size. Here are the keys 1 to 12:
$ seq 1 12 | awk '{ a[$1] } END { for (k in a) printf "%s ", k; print "" }'
2 3 4 5 6 7 8 9 10 11 12 1
"1" is the single byte 49, so it lands in bucket 49, the last of 50. "2" is 50, which is bucket 0. "10" is 49 × 31 + 48 = 1567, bucket 17.
To check that I had the whole mechanism right, I wrote a 27-line Python model of hash, setsymtab, rehash and instat and compared its order with awk’s. On seq 1 1000 both give the same 1,000 keys in the same order, after rehashes at 101 and 401 elements. On a file of 100,000 numbers with 43,282 distinct values they agree on all 43,282 keys, after five rehashes, ending at 51,200 buckets. awk gives the same order every time:
$ for i in 1 2 3; do awk '{a[$1]} END { for (k in a) printf "%s ", k; print "" }' nums.txt | md5; done
eb8827de09edf72b17585c874013fb27
eb8827de09edf72b17585c874013fb27
eb8827de09edf72b17585c874013fb27
The loop saves cnext before it runs the body, so the body can delete the current element. Deleting every element from inside the loop works: awk 'BEGIN { for (i = 1; i <= 1000; i++) a[i]; for (k in a) { delete a[k]; n++ }; print n, length(a) }' prints 1000 0. The comment “this routine knows too much” is already in the Seventh Edition code, which also walked the buckets directly.
The FIXES file records one attempt to make the order sorted. The entry for 6 May 1991 says: “changed for (i in array) to access elements in sorted order. then unchanged it – it really does run slower in too many cases. left the code in place, commented out.”
How even is the spread
The model also gives the chain lengths. For the 43,282 numeric keys in 51,200 buckets (load 0.845), compared with what a perfectly random hash would give (a Poisson distribution with the same load):
| Chain length | Buckets | Random hash |
|---|---|---|
| 0 | 27,620 | 21,986 |
| 1 | 12,307 | 18,586 |
| 2 | 6,069 | 7,856 |
| 3 | 3,080 | 2,214 |
| 4 | 1,360 | 468 |
| 5 | 509 | 79 |
| 6 | 186 | 11 |
| 7 | 56 | 1 |
| 8 | 13 | 0 |
More than half the buckets are empty and 13 chains have 8 entries. The keys are decimal strings, built from only ten byte values, and I didn’t work out which property of the hash makes them clump. Lookups stay short anyway. In the model, finding an existing key walks 1.76 cells on average.
Subscripts are strings
Since keys are strings, two numbers that print the same are the same key, and two strings that mean the same number are not:
$ awk 'BEGIN { a[0.1 + 0.2]; a[0.3]; for (k in a) print "[" k "]" }'
[0.3]
$ awk 'BEGIN { b[1e6]; b[1000000]; for (k in b) print "<" k ">" }'
<1000000>
$ printf '57\n057\n57.0\n\n' | awk '{ n[$1]++ } END { for (k in n) print "[" k "]", n[k] }'
[] 1
[57.0] 1
[057] 1
[57] 1
0.1 + 0.2 is not exactly 0.3 as a double, but %.6g turns both into "0.3". A field like $1 keeps the text it was read as, so 057 stays 057. The empty line got its own element with the empty string as key. This awk converts a whole number with "%.30g" rather than "%d", which gives the same digits for any integer a double can hold exactly.
Curious facts
- In Seventh Edition Unix (1979), every awk array had 16 buckets, forever.
MAXSYMwas 16, the hash added up the bytes of the key, and there was no rehash. Anagrams always collided, since"57"and"75"both sum to 108. - The same
Cellstructure holds variables, fields and array elements. The global variables are themselves a hash table,symtab, andmain.ccreates it withmakesymtab(NSYMTAB/NSYMTAB), which is one bucket. It grows like any array. - Nothing ever shrinks a table.
delete a[k]frees one cell and leaves the bucket array at its largest size. Onlydelete awith no subscript frees everything and starts again with 50 buckets (awkdeleteinrun.c). - Apple’s FIXES file has an entry dated 16 February 2021, adding multibyte support, while the version string still says 20200816.
- The FIXES file lists changes “made since the AWK book was sent to the printers in August, 1987.”
History
- 1977: awk is written at AT&T Bell Laboratories, according to the gawk manual’s history section.
- 1979: the Seventh Edition awk: 16 fixed buckets (
#define MAXSYM 16), additive hash,for (k in a)walks the buckets with the comment “this routine knows too much”. - 1985: the Research Unix Eighth Edition awk: 50 fixed buckets and the multiply-by-31 hash, still without growth.
- 1989: the System V Release 4 awk (as later published in OpenSolaris) has the current design:
NSYMTAB50,FULLTAB2,GROWTAB4. - May 1991: sorted
for (k in a)is tried and reverted. - May 1992:
rehashjust returns when it can’t get memory, and the table keeps its size. - 2020: version 20200816, the one macOS still reports.
Sources
- Apple awk-40
src/awk.h:Awkfloat,CellandArray,NSYMTAB - Apple awk-40
src/tran.c:FULLTABandGROWTAB,makesymtab,setsymtab,hash,rehash,lookup,"%.30g" - Apple awk-40:
run.cinstat,main.cversion andsymtab, FIXES, 16 February 2021, 31 May 1992, 6 May 1991 - Seventh Edition Unix:
awk.defMAXSYM,tran.chash,run.cfor-in - danfuzz/one-true-awk archive (versions README): 1985-08-03
tran.candawk.h; 1989-10-11tran.candawk.h - onetrueawk/awk (upstream, tags 20180827 and 20220122 on either side of 20200816)
- POSIX.1-2024
awk; gawk manual, “History”
grep -rl /lib/unix/awk-arrays/
ls unix/
- draft How sort(1) sorts more data than fits in memoryHow the sort on macOS and FreeBSD splits big input into sorted temporary files and merges them back, how much memory it allows itself, and why the locale matters more than the algorithm.