haskell-performance
Performance patterns for production Haskell. Use when diagnosing space leaks, choosing between strict and lazy data structures, optimising hot paths, setting up profiling with GHC cost centres, or benchmarking with criterion.
Unsigned, install at your own risk
UnverifiedThis skill has no cryptographic signature attached. We can't verify the contents match what the publisher intended.
Install this skill
No account required. Pick your tool, or use the command that detects it for you.
Run in your terminal. It detects your AI tool.
npx @skills-hub-ai/cli install pragmatic-haskell-haskell-performanceManual setup by platform
Claude Code
~/.claude/skills/pragmatic-haskell-haskell-performance/SKILL.md
Instructions
Haskell Performance
The Guiding Principle
Optimise only when you have a measurement. Premature optimisation introduces
complexity without verified benefit. The correct order is: make it correct,
measure it, then make it fast.
Strict by Default
Haskell is lazy by default, which means unevaluated expressions (thunks)
accumulate silently. Most production code should be strict.
Data type fields
Mark all constructor fields strict with ! unless you have a specific reason
to defer evaluation:
-- Bad — lazy fields accumulate thunks, causing space leaks
data Config = Config
{ configHost :: Text
, configPort :: Int
, configTimeout :: Int
}
-- Good — fields evaluated when the record is constructed
data Config = Config
{ configHost :: !Text
, configPort :: !Int
, configTimeout :: !Int
} deriving stock (Eq, Show)
For modules with many data types, enable StrictData at the top of the file
rather than annotating every field individually:
{-# LANGUAGE StrictData #-}
Left folds
Never use foldl when accumulating a strict value. It builds a chain of
unevaluated thunks that overflows the stack on large inputs:
import Data.List (foldl')
-- Bad — stack overflow on large lists
sumBad :: [Int] -> Int
sumBad = foldl (+) 0
-- Good — constant stack space
sumGood :: [Int] -> Int
sumGood = foldl' (+) 0
Strict Containers
Prefer the strict variants of standard containers:
| Use this | Not this |
|---|---|
Data.Map.Strict | Data.Map.Lazy |
Data.HashMap.Strict (from unordered-containers) | Data.HashMap.Lazy |
Data.IntMap.Strict | Data.IntMap.Lazy |
Data.Sequence | Cons-list for queue-like operations |
Data.Text | String |
Data.ByteString | Lazy ByteString for in-memory buffers |
The lazy variants are useful only when you intentionally need incremental
evaluation (e.g. streaming a very large map). Document the reason when
using them.
The UNPACK Pragma
For small primitive fields (Int, Double, Word, Bool) in hot data
types, {-# UNPACK #-} eliminates the pointer indirection:
data Point = Point
{ pointX :: {-# UNPACK #-} !Double
, pointY :: {-# UNPACK #-} !Double
} deriving stock (Eq, Show)
Rules:
- Only apply to fields that are already strict (
!). - Only worth it for primitive types or small newtypes wrapping primitives.
- Do not apply to fields that are
Maybe, tuples, or algebraic types — the
unboxing cost outweighs the benefit.
Alternatively, use -funbox-strict-fields in ghc-options to unbox all
strict fields automatically. This is a blunt instrument; prefer explicit
UNPACK for types where you have measured a benefit.
Detecting Thunks with nothunks
For long-lived data structures (caches, application state, session stores),
use the nothunks library to assert in tests that no unexpected thunks are
retained:
import NoThunks.Class (NoThunks (..), noThunks)
data AppState = AppState
{ stateUsers :: !(Map UserId User)
, stateSettings :: !Settings
} deriving stock (Show)
deriving anyclass (NoThunks)
-- In your test suite:
it "AppState contains no unexpected thunks" $ do
let s = initialState
result <- noThunks [] s
result `shouldBe` Nothing
NoThunks can be derived with anyclass when all fields are strict and
themselves implement NoThunks. For types that intentionally contain
thunks, implement the instance manually and whitelist them.
Profiling
Enabling cost centres
Build with profiling support:
cabal build --enable-profiling --ghc-options="-fprof-auto -rtsopts"
Run with RTS profiling flags:
./my-app +RTS -p -hc -RTS
This produces:
my-app.prof— time and allocation profile by cost centremy-app.hp— heap profile (view withhp2prettyorhp2ps)
Reading the .prof file
Focus on the columns:
%time— fraction of time spent in this cost centre%alloc— fraction of allocations attributed hereticks— raw time ticks (proportional to wall time)
A function with high %alloc but low %time is allocating heavily but not
slow — it may be fine if GC can reclaim quickly. High %time with low
%alloc often indicates CPU-bound work. High %alloc combined with high
%time suggests allocation pressure worth investigating.
Heap profiles
Convert the .hp file to an SVG:
hp2pretty my-app.hp
Look for:
- Monotonically growing heap — a space leak
- A single type dominating the heap — the source of the leak
- Repeated allocation/GC sawtooth — normal but check the amplitude
Benchmarking with criterion
Use criterion for micro-benchmarks. Always benchmark with a warm-up
run and statistical analysis rather than measuring wall time manually.
{-# LANGUAGE OverloadedStrings #-}
module Main (main) where
import Criterion.Main
import MyApp.User.Validation (validateCreateUser)
import MyApp.User.Fixtures (validRequest)
main :: IO ()
main = defaultMain
[ bgroup "validateCreateUser"
[ bench "valid input" $ nf validateCreateUser validRequest
, bench "invalid name" $ nf validateCreateUser (validRequest { reqName = "X" })
]
]
Use nf (normal form) to force full evaluation of the result. Use whnf
only when you specifically want to measure evaluation to weak head normal form.
Add benchmarks as a benchmark stanza in the cabal file:
benchmark myapp-bench
type: exitcode-stdio-1.0
hs-source-dirs: bench
main-is: Main.hs
default-language: GHC2021
build-depends:
, base
, criterion
, myapp
, myapp-test-lib -- reuse fixtures and generators
Common Performance Anti-Patterns
| Pattern | Problem | Fix |
|---|---|---|
foldl | Thunk accumulation, stack overflow | foldl' |
Data.List.nub | O(n²) | Set.toList . Set.fromList or nubOrd |
++ in a loop | O(n) per append, O(n²) overall | Data.DList or accumulate in reverse then reverse once |
length on a list | O(n) | Keep a counter separately, or use Data.Sequence |
show on large values for logging | Allocates the whole string | Use prettyprinter with lazy rendering |
Lazy Text / ByteString for in-memory buffers | Fragmented, extra indirection | Strict Text / ByteString |
String for performance-sensitive paths | Linked list of Char; slow | Text or ByteString |
Map.insertWith on Data.Map.Lazy | Values not evaluated on insert | Data.Map.Strict |
Security
Reviews (0)
More from Pragmatic Haskell
View source →More Build skills
Browse category →Frequently asked questions about haskell-performance
What does the haskell-performance skill do?
Performance patterns for production Haskell. Use when diagnosing space leaks, choosing between strict and lazy data structures, optimising hot paths, setting up profiling with GHC cost centres, or benchmarking with criterion. It's a reusable SKILL.md instruction set that loads into your AI coding assistant on demand, no prompt engineering, no copy-pasting every session.
How do I install the haskell-performance skill?
Run `npx @skills-hub-ai/cli install pragmatic-haskell-haskell-performance` from your terminal. The CLI writes the SKILL.md to the correct location for your AI tool (e.g. ~/.claude/skills/pragmatic-haskell-haskell-performance/ for Claude Code or ~/.cursor/skills/ for Cursor with --target cursor) and adds it to your project's .skills.json lockfile.
Which AI tools does haskell-performance work with?
haskell-performance runs in Claude Code. It follows the open Agent Skills standard (SKILL.md), so the same skill works in every supported tool without modification.
Is the haskell-performance skill free?
Yes. Every skill on skills-hub.ai is free and open-source. There are no premium tiers, paywalls, or usage limits. You only pay for whatever AI assistant you're already using.
How do I use haskell-performance after installing it?
In Claude Code, type `/pragmatic-haskell-haskell-performance` (or whatever slash command the skill registers) and the AI follows the skill's instructions immediately. You can also reference it by name in natural language, your AI loads the skill into context when relevant.
Can I share the haskell-performance skill with my team?
Yes. Commit your project's .skills.json lockfile and teammates run `npx @skills-hub-ai/cli install` (no args) to install every skill at the exact version you pinned. Organization-scoped installs work via skills-hub.ai organizations.