Haskell Data.Vector Tutorial for Fast Numeric Arrays
Your program reads 8 million sensor readings, sums them, and takes nineteen seconds while resident memory climbs past 900 MB. The logic is six lines long and obviously correct.

Your program reads 8 million sensor readings, sums them, and takes nineteen seconds while resident memory climbs past 900 MB. The logic is six lines long and obviously correct. The container is the problem: a list of Doubles costs roughly 48 bytes per element once you count the cons cell and the boxed value, and every arithmetic step allocates.
Data.Vector is the usual answer, and the introductions stop one step too early. They show fromList, indexing and sum, then leave you to discover on your own that there are four vector modules, that the fast one needs a type class you have never imported, and that the obvious way to build a vector element by element is the slowest thing in the library. This tutorial assumes you can read a type signature and have used Data.Map before; if ordered key lookups are what you actually need, the guide to Data.Map for fast key value lookups is the better starting point.
What a vector gives you that a list does not
A Haskell list is a linked structure. Each element sits in a cons cell that holds a pointer to the value and a pointer to the rest. Indexing element 400,000 means following 400,000 pointers, scattered across the heap, missing cache on most of them.
A vector is one contiguous block. Indexing is constant time, the prefetcher can actually predict what comes next, and the length is stored rather than computed. On my teaching laptop, a 2021 ThinkPad with a four core i5, summing 10 million Int values took 164 milliseconds as a list and 9 milliseconds as an unboxed vector. The memory difference was larger than the time difference: around 480 MB against 80 MB.
That 80 MB figure is the real headline. An unboxed vector of 10 million Int values stores exactly 10 million machine words and nothing else. No pointers, no heap objects per element, no thunks.
Four modules, and how to pick one in ten seconds
This is the fork that confuses people, because every tutorial uses a different import and never says why.
| Module | Holds | Needs | Use it when |
|---|---|---|---|
| Data.Vector | Pointers to boxed values | Nothing | Elements are records, strings, or sum types |
| Data.Vector.Unboxed | Raw values, no pointers | An Unbox instance | Int, Double, Bool, Char, and tuples of those |
| Data.Vector.Storable | Raw values in pinned memory | A Storable instance | You pass the buffer to a C library |
| Data.Vector.Primitive | Raw machine types only | A Prim instance | Rarely chosen directly |
Default to Data.Vector.Unboxed, imported qualified as U, whenever your elements are numbers or booleans. The Unbox instance already exists for every primitive type and for tuples up to six elements, so a vector of pairs of Doubles works without you writing anything. Reach for the boxed Data.Vector only when the element type will not fit, which in practice means records, Text, Maybe, and your own data types.
Storable matters for one specific case: handing a buffer to C without copying. If you call into a numerical C library, that is the module that gives you a pointer you can pass through the foreign function interface.
Building vectors without quadratic blowups
Vectors are immutable, so snoc returns a brand new vector with the whole block copied. Appending in a loop is O(n squared). I have seen a student program spend four minutes building a 200,000 element vector that should have taken milliseconds, and nothing in the type signature hints at the cost.
- U.fromList when you already have the list. The list is consumed as it is traversed, so the memory spike is smaller than people fear.
- U.generate n f when element i is a pure function of its index. This is the cleanest way to build lookup tables.
- U.replicate and U.enumFromN for constant fills and arithmetic ranges.
- U.unfoldrN when you are generating from a seed and know the upper bound, which covers most parsers and simulations.
- U.create with a mutable vector inside, for anything genuinely imperative.
That last one is worth a paragraph. Inside U.create you get a mutable vector in the ST monad, write to it with MU.write or MU.modify in a loop, and the library freezes it into an immutable vector when the block ends. No copying happens at the freeze step, and the mutability never escapes, so the result is still a pure value. A histogram over 50 million events is the textbook case: allocate 256 buckets once, increment in place, freeze.
Why the advice to replace every list with a vector is wrong
The common recommendation, once someone discovers vector, is to convert every list in the codebase. I have watched this make programs slower and uglier, and I have done it myself on a parser that got 15 percent worse.
Lists in GHC are not the array you think they are. When a list is produced and consumed in one pipeline, the optimiser fuses the stages and the cons cells are often never allocated at all. A sum over a filtered map over enumFromTo compiles to a loop with an accumulator and no heap traffic. The list was never a data structure in that program, it was control flow in disguise.
Vector fuses too, through its stream representation, and it fuses well. The difference shows up at the boundaries. Every fromList and toList is a real traversal, and a pipeline that converts back and forth twice can cost more than the list version it replaced.
Three honest criteria. Use a vector when the data is read many times after it is built, when you index by position, or when element count is large enough that per element overhead dominates, which for numbers starts around 50,000. Keep lists for streaming pipelines, for anything where you repeatedly take the front, and for the dozen element configuration list that nobody will ever profile. I keep lists in far more places than my students expect after reading a benchmark post.
The gotchas that cost me real time
The bang operator U.! is unchecked in release builds of some setups and throws an unhelpful error in others. Use U.!? during development, which returns a Maybe, and move to the unsafe variants only after a profile says bounds checking is on the hot path. I have never once had bounds checks show up as the top cost centre in a program that was actually slow.
U.slice is a view, not a copy, and takes constant time. That is excellent for windowed calculations, and it also means the slice keeps the entire original block alive. Slicing 100 elements out of a 40 million element vector and holding the slice for the rest of the program retains all 40 million. U.force makes a compact copy and releases the rest. This particular mistake looks exactly like a leak in a heap profile, and the piece on finding and fixing a Haskell space leak covers how to tell the two apart.
A boxed Data.Vector of lazily computed values is a thunk farm. U.generate on an unboxed vector evaluates every element eagerly, which is almost always what you want, but V.generate on a boxed vector stores unevaluated closures. If you see memory grow after building a vector rather than during, that is the cause.
One more: the Unbox instance for tuples stores each field in its own separate array behind the scenes. That is a performance win for column oriented access and a surprise if you expected an array of structs layout when calling out to C.
A measurement worth running this week
Take the slowest numeric loop in your project and write both versions. Keep the list version, add an unboxed vector version, and compile both with optimisation enabled. Then run with the runtime statistics flag so you see total allocation, not just wall clock. Allocation in bytes is the number that tells you whether fusion happened, and it is far steadier across runs than timing on a laptop with a busy fan.
If total allocation for the vector version is within a few kilobytes of a fixed constant, your pipeline fused and the loop is as tight as it gets. If allocation scales with input size, something broke fusion, usually an intermediate toList or a lambda the optimiser could not see through. More guides in the same spirit are collected in the tutorials section.
Frequently asked questions
Which vector module should I import by default?
Data.Vector.Unboxed, qualified as U, if your elements are Int, Double, Bool, Char or tuples of those. Switch to the plain Data.Vector only when the element type has no Unbox instance, such as records, Text or Maybe values.
Is Data.Vector part of GHC?
No. The containers package ships with GHC, but vector is a separate package you add to build-depends. It is maintained, widely used, and has very few dependencies of its own, so adding it is a low risk decision.
How do I update a single element in a vector?
For a one off change, U.// takes a list of index and value pairs and returns a new vector, copying the block. For many updates, build with U.create or U.modify and write in place with the mutable interface, which avoids a copy per update.
Why is my vector code slower than the list version?
Check for conversions. A fromList or toList in the middle of a pipeline breaks fusion and adds a full traversal. Also confirm you compiled with optimisation turned on, because vector relies heavily on the optimiser and is genuinely slow without it.
More in Tutorials
Tutorials
Haskell Reader Monad Tutorial for App Configuration
You start a service with one configuration field, a database connection string.
Tutorials
Haskell traverse and sequenceA for Everyday Code
You wrote a function that parses one line of a config file and hands back a Maybe Int.
Tutorials
Haskell State Monad Tutorial With a Working Example
You have a function that needs a counter, a random seed or a running total, and passing that value in and out of every call has...