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 NN nodes and EE 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 10,000×10,000=10810{,}000 \times 10{,}000 = 10^8 cells. Only 50,000/108=0.05%50{,}000 / 10^8 = 0.05\% are nonzero — 99.95% wasted space, ~400 MB of zeros. And iterating a row still touches all NN cells even if only 5 are nonzero.

The CSR Solution

Give each node an integer index 0…N−10 \ldots N{-}1 and store everything in three flat arrays:

  • indptr (length N+1N{+}1): bookmarks — indptr[i] says where node ii's neighbors start
  • indices (length EE): all destination nodes packed sequentially, section by section
  • weights (length EE): edge weights, parallel to indices — weights[k] is the weight of the edge to indices[k]

To find neighbors of node ii:

neighbors(i)=indices[ indptr[i]  :  indptr[i+1] ]\text{neighbors}(i) = \texttt{indices}[\,\texttt{indptr}[i] \;:\; \texttt{indptr}[i{+}1]\,]

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 ii'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 EE.

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: 55 nodes and 66 weighted edges: 0→1 (0.7), 0→2 (0.3), 1→3 (0.9), 3→0 (0.5), 3→4 (0.8), 4→2 (0.4)0 \to 1\ (0.7),\allowbreak\ 0 \to 2\ (0.3),\allowbreak\ 1 \to 3\ (0.9),\allowbreak\ 3 \to 0\ (0.5),\allowbreak\ 3 \to 4\ (0.8),\allowbreak\ 4 \to 2\ (0.4). The conversion is three passes.

  1. Count. For every edge, add one to a counter for its source node. The out-degrees of nodes 0 to 44 come out as [2, 1, 0, 2, 1][2,\ 1,\ 0,\ 2,\ 1]. Implementations usually keep these counters directly in indptr, one slot to the right of the node, so that indptr[0] stays zero.
  2. Prefix sum. Replace each counter by the running total of the ones before it. The counts become bookmarks: indptr=[0, 2, 3, 3, 5, 6]\texttt{indptr} = [0,\ 2,\ 3,\ 3,\ 5,\ 6]. Node 2's count was zero, so its two bookmarks are equal, and the last bookmark equals the number of edges.
  3. Scatter. Give each node a cursor that starts at its own bookmark. Walk the edge list once more; each edge writes its target into indices and its weight into weights at its source's cursor, and the cursor moves one slot. The result is indices=[1, 2, 3, 0, 4, 2]\texttt{indices} = [1,\ 2,\ 3,\ 0,\ 4,\ 2] and weights=[0.7, 0.3, 0.9, 0.5, 0.8, 0.4]\texttt{weights} = [0.7,\ 0.3,\ 0.9,\ 0.5,\ 0.8,\ 0.4].

Each pass is linear, so the whole conversion costs O(N+E)O(N + E) 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 O(log⁡d)O(\log d) for a node of degree dd, 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 O(1)O(1) 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 EE, 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 — EE integers — with indptr — N+1N{+}1 integers. On the card's graph the sorted row array is [0, 0, 1, 3, 3, 4][0,\ 0,\ 1,\ 3,\ 3,\ 4], 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 ii?" and CSC answers "who points to ii?". CSC of a matrix has exactly the arrays of CSR of its transpose, which is how the card's graph gets its CSC: indptr=[0, 1, 2, 4, 5, 6]\texttt{indptr} = [0,\ 1,\ 2,\ 4,\ 5,\ 6] and indices=[3, 0, 0, 4, 1, 3]\texttt{indices} = [3,\ 0,\ 0,\ 4,\ 1,\ 3], where indices now holds sources. Node 2, which has no outgoing edges, has incoming ones: the slice from 22 to 44 names nodes 0, 40,\ 4.

PropertyCOOCSRCSC
Index storage2E2EE+N+1E + N + 1E+N+1E + N + 1
Append one edgeO(1)O(1)O(N+E)O(N + E)O(N+E)O(N + E)
Out-neighbours of iiscan all edgesone slicescan all edges
In-neighbours of iiscan all edgesscan all edgesone slice
Good forbuilding, files, conversionrow slicing, y=Axy = Ax, push traversalcolumn slicing, y=A⊤xy = A^\top x, 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 O(1)O(1) neighbor access asymptotically. The speedup comes from constants:

FactorHash MapCSR
Neighbor lookupHash + bucket walk + equality checkTwo integer array reads
IterationRandom heap access per entryContiguous memory slice
Memory per edgeKey object + value object + bucket pointerOne int32 + one float64 = 12 bytes
Cache behaviorPointer chasing, cache missesSequential access, prefetcher-friendly
SIMD potentialNone (Python objects)numpy vectorizes with SIMD

The constant factor difference is typically 10-30x for graph traversal workloads. This comes from three sources:

  1. Zero hashing — 295M hash calls become zero
  2. Cache locality — contiguous arrays fit L1/L2 cache, no pointer chasing
  3. 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 ii (reverse lookup) is O(E)O(E) 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 O(N+E)O(N + E) time and pays for itself on the first full traversal.

Updating a CSR Graph

Why is one edit so expensive? Add the edge 1→21 \to 2 to the card's graph (click that cell of the matrix). The new entry belongs in node 11's slice, at position 22 of indices. Every entry after it — 44 of them — moves one slot to the right, and every bookmark after node 11 — 44 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 SparseMatrix has an uncompressed mode for exactly this, filled after reserve() with the expected number of entries per column, and makeCompressed() 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 older csr_matrix) exposes the three arrays as indptr, indices and data. scipy.sparse.csgraph runs shortest paths, connected components and other graph algorithms directly on sparse matrices, and NetworkX's to_scipy_sparse_array returns 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 arrays crow_indices, col_indices and values.
  • 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.