CSR: How Graphs Are Stored in Flat Arrays
Click a node, or step through the nodes with the slider, to see which sections of the arrays correspond to its neighbors: its two indptr bookmarks point at the ends of its slice. Try node 2 to see what an empty range looks like. Click a cell of the dense matrix to add or remove that edge and watch the arrays rebuild, or click any array cell to find which node owns it.
A five-node weighted directed graph beside its dense adjacency matrix and its three CSR arrays; selecting a node highlights its slice of indices and weights between its two indptr bookmarks, and toggling a matrix cell adds or removes an edge and rebuilds the arrays.
The Problem: Nested Maps Are Expensive
A graph with nodes and edges is typically stored as a nested map — graph[node_i][node_j] = weight. Every time you ask "who are node 0's neighbors?", the runtime hashes the key, walks hash buckets, checks equality, returns an inner map (another hash-based structure on the heap), and iterates over it — with hash + equality on every neighbor. Each weight is a separate heap-allocated object.
Data is scattered across memory. The CPU cache prefetcher can't help — every access is a random pointer chase.
For algorithms like PageRank or PPR that iterate over all neighbors millions of times, this overhead dominates. In one real profile, FragmentId.__hash__ alone accounted for 295 million calls and 14.4 seconds of CPU time — and that's just the hashing, not the dict lookups themselves.
How about a full matrix?
For a graph with 10,000 nodes and average degree 5, you have ~50,000 edges. A full adjacency matrix would be cells. Only are nonzero — 99.95% wasted space, ~400 MB of zeros. And iterating a row still touches all cells even if only 5 are nonzero.
The CSR Solution
Give each node an integer index and store everything in three flat arrays:
- indptr (length ): bookmarks —
indptr[i]says where node 's neighbors start - indices (length ): all destination nodes packed sequentially, section by section
- weights (length ): edge weights, parallel to indices —
weights[k]is the weight of the edge toindices[k]
To find neighbors of node :
The indptr trick
Think of it like a family shopping list. Everyone's items are written on one long list, and a separate slip of paper says "lines 1-5 are for mom, lines 6-7 for dad, lines 8-12 for grandma". The list is indices. The slip with line ranges is indptr.
When indptr[i] == indptr[i+1], the range is empty — that node has no outgoing edges. Node 2 demonstrates this: indptr[2] = 3 and indptr[3] = 3, so indices[3:3] is an empty slice.
The difference indptr[i+1] - indptr[i] is node 's out-degree, so the degree of every node is free: no counting, no extra array. The last bookmark, indptr[N], is the number of edges .
Building the Arrays from an Edge List
Graphs rarely arrive as CSR. They arrive as a list of edges — rows of a table, lines of a file — and the conversion is a counting sort by source node. Take the card's starting graph: nodes and weighted edges: . The conversion is three passes.
- Count. For every edge, add one to a counter for its source node. The out-degrees of nodes 0 to come out as . Implementations usually keep these counters directly in
indptr, one slot to the right of the node, so thatindptr[0]stays zero. - Prefix sum. Replace each counter by the running total of the ones before it. The counts become bookmarks: . Node 2's count was zero, so its two bookmarks are equal, and the last bookmark equals the number of edges.
- Scatter. Give each node a cursor that starts at its own bookmark. Walk the edge list once more; each edge writes its target into
indicesand its weight intoweightsat its source's cursor, and the cursor moves one slot. The result is and .
Each pass is linear, so the whole conversion costs time with no comparison sort.
The scatter keeps the edges of one node in the order they came in. Algorithms that test for one edge by binary search, in for a node of degree , or merge two rows want each row sorted by target; SciPy tracks this as has_sorted_indices and fixes it with sort_indices(). The card's toCsr sorts the edges by (source, target) before counting, which produces the same three arrays with every row already sorted.
Duplicate edges need a decision too. SciPy's COO documentation states that duplicate entries are summed on conversion to CSR or CSC; if duplicates mean something else in your data, remove them before converting.
Why "Compressed Sparse Row"
- Compressed — zeros are not stored
- Sparse — designed for data where most entries are zero
- Row — traversal is by row (source node); for column-major access there's CSC (Compressed Sparse Column)
The format is older than its name: it is also known as the Yale format, after the Yale Sparse Matrix Package, and in SciPy the third array is called data rather than weights.
CSR vs Adjacency List
An adjacency list — in Python a list of lists, in C++ a vector<vector<int>> — stores the same thing as CSR: for each node, the nodes it points to. The difference is where those lists live. An adjacency list allocates each node's list separately; each one carries its own pointer, length and spare capacity, and the lists end up wherever the allocator put them. CSR takes all of those lists, writes them one after another into a single array, and keeps only where each one starts.
The trade is flexibility for density. Appending an edge to an adjacency list is amortised and touches one node's list; in CSR it shifts every later entry. An adjacency list pays a pointer, a length, spare capacity and the allocator's overhead per node, where CSR pays one integer. And walking all edges of an adjacency list jumps between separate allocations, where CSR reads two arrays from start to end.
So "CSR vs adjacency list" is not a choice between two ideas. CSR is the adjacency list, frozen and packed. Build the graph in the flexible form, freeze it into CSR when it stops changing.
CSR vs COO vs CSC
There are three common ways to lay out the same nonzeros, and converting between them is linear.
COO (coordinate format) stores one triple per edge: a row array, a col array and a data array, all of length , in any order. It is the edge list itself: appending an edge is appending three numbers, and it is the natural format for files (Matrix Market's coordinate format). What it lacks is an index: finding the edges of one node means scanning all of them.
CSR sorts COO by row and replaces the row array — integers — with indptr — integers. On the card's graph the sorted row array is , and indptr is that array with each run of equal values collapsed into a bookmark. Rows become slices.
CSC does the same by column: sort by target and compress the target array instead. For a graph, CSR answers "where can I go from ?" and CSC answers "who points to ?". CSC of a matrix has exactly the arrays of CSR of its transpose, which is how the card's graph gets its CSC: and , where indices now holds sources. Node 2, which has no outgoing edges, has incoming ones: the slice from to names nodes .
| Property | COO | CSR | CSC |
|---|---|---|---|
| Index storage | |||
| Append one edge | |||
| Out-neighbours of | scan all edges | one slice | scan all edges |
| In-neighbours of | scan all edges | scan all edges | one slice |
| Good for | building, files, conversion | row slicing, , push traversal | column slicing, , pull traversal, direct solvers |
COO wins while the graph is being assembled or loaded and as the interchange format between libraries; CSR when the computation reads rows, such as a BFS that pushes from its frontier; CSC when it reads columns, such as PageRank written as a pull, where each node sums the contributions of the nodes pointing at it. Sparse direct solvers such as CHOLMOD in SuiteSparse work by column, and MATLAB stores its sparse matrices in compressed column form.
When an algorithm needs both directions, the usual answer is to store both, CSR and CSC, and pay twice the memory for neighbours in either direction as a slice.
Performance: Same Big-O, Different Constants
Both hash maps and CSR give neighbor access asymptotically. The speedup comes from constants:
| Factor | Hash Map | CSR |
|---|---|---|
| Neighbor lookup | Hash + bucket walk + equality check | Two integer array reads |
| Iteration | Random heap access per entry | Contiguous memory slice |
| Memory per edge | Key object + value object + bucket pointer | One int32 + one float64 = 12 bytes |
| Cache behavior | Pointer chasing, cache misses | Sequential access, prefetcher-friendly |
| SIMD potential | None (Python objects) | numpy vectorizes with SIMD |
The constant factor difference is typically 10-30x for graph traversal workloads. This comes from three sources:
- Zero hashing — 295M hash calls become zero
- Cache locality — contiguous arrays fit L1/L2 cache, no pointer chasing
- Vectorization — numpy operations on flat arrays use SIMD instructions
Where the cache helps, and where it does not
CSR makes one half of a traversal sequential. In a PageRank step or a matrix–vector product, the loop reads indptr, indices and weights from start to end: those reads stream through memory, and the hardware prefetcher keeps them ahead of the CPU.
The other half is not sequential. For every edge the loop also reads a value belonging to the neighbour — rank[indices[k]], x[indices[k]] — and those reads land wherever the neighbour's number points. That is a gather, and on a large graph it is where most of the cache misses come from. CSR does not fix it; the node numbering does. If nodes that are connected get nearby numbers, their values sit in the same cache lines. Reverse Cuthill–McKee, available as reverse_cuthill_mckee in scipy.sparse.csgraph, renumbers nodes to pull nonzeros toward the diagonal for exactly this reason.
Index width matters for the same reason. 32-bit indices take half the memory traffic of 64-bit ones. SciPy uses int32 indices whenever the sizes allow it and switches to int64 only when they do not.
When NOT to Use CSR
CSR is optimized for read-heavy, write-once graphs:
- Dynamic graphs — inserting or removing an edge requires rebuilding the arrays. If your graph changes frequently, an adjacency list or edge list is better.
- Column access — finding all nodes that point to node (reverse lookup) is in CSR. Use CSC for that, or store both.
- Very dense graphs — if most cells are nonzero, a plain matrix is simpler and has less overhead from indptr bookkeeping.
The typical pattern: build your graph using whatever is convenient (dict-of-dict, edge list), then convert to CSR once before the compute-heavy phase. Conversion costs time and pays for itself on the first full traversal.
Updating a CSR Graph
Why is one edit so expensive? Add the edge to the card's graph (click that cell of the matrix). The new entry belongs in node 's slice, at position of indices. Every entry after it — of them — moves one slot to the right, and every bookmark after node — of them — grows by one. Removing an edge is the same in reverse. SciPy says so directly: changing the sparsity structure of a CSR matrix emits a SparseEfficiencyWarning that suggests the LIL format instead.
Changing a weight touches one cell of weights and nothing else; only the structure is costly to change.
Systems that need a changing graph and fast reads use a few standard workarounds:
- Batch and rebuild. Collect changes in a COO buffer and rebuild CSR every so many changes. A rebuild is linear, so a batch costs about as much as one edit.
- Delta buffer. Keep the CSR immutable and put new edges in a small side structure, deleted ones in a set of tombstones. A neighbour query reads the CSR slice, skips the tombstones and adds the delta; when the delta grows past a threshold, merge it into a new CSR. SuiteSparse:GraphBLAS works this way internally: insertions wait as "pending tuples", deletions are marked as "zombies", and both are folded into the matrix when a result needs it.
- Slack in each row. Leave empty slots at the end of each row, so an insertion fills a gap instead of shifting the rest of the array. Eigen's
SparseMatrixhas an uncompressed mode for exactly this, filled afterreserve()with the expected number of entries per column, andmakeCompressed()squeezes the gaps out again. Packed CSR (Wheatman and Xu, IEEE HPEC 2018) spreads the gaps through the edge array as a packed memory array so that updates stay cheap without a rebuild. - Soft deletion. Mark a deleted edge instead of removing it — a zero weight, a sentinel target — and compact later. In SciPy an explicitly stored zero stays in the structure until
eliminate_zeros()removes it.
Where CSR Is Used
CSR, with CSC beside it, is the compute format of most sparse software:
- SciPy:
scipy.sparse.csr_array(and the oldercsr_matrix) exposes the three arrays asindptr,indicesanddata.scipy.sparse.csgraphruns shortest paths, connected components and other graph algorithms directly on sparse matrices, and NetworkX'sto_scipy_sparse_arrayreturns CSR by default. - Linear algebra libraries: NVIDIA cuSPARSE and Intel oneMKL both provide sparse matrix–vector and matrix–matrix products on CSR.
- PyTorch: sparse CSR tensors (
torch.sparse_csr_tensor) name the arrayscrow_indices,col_indicesandvalues. - Graph engines: SuiteSparse:GraphBLAS stores a matrix by row or by column, the CSR and CSC layouts, with a hypersparse variant for matrices with many empty rows.
- GNN libraries: DGL can keep a graph in COO, CSR and CSC formats at once and creates them as operations need them. PyTorch Geometric's basic graph representation,
edge_index, is COO: a two-row tensor of sources and targets.
The pattern is the same everywhere: COO to assemble, CSR or CSC to compute.