Skip to main content

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.

v1.0.0New

Unsigned, install at your own risk

Unverified

This 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-performance
Or get the file:
Browse all CLI commands →
Manual setup by platform

Claude Code

~/.claude/skills/pragmatic-haskell-haskell-performance/SKILL.md

Setup guide →
0Save

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 thisNot this
Data.Map.StrictData.Map.Lazy
Data.HashMap.Strict (from unordered-containers)Data.HashMap.Lazy
Data.IntMap.StrictData.IntMap.Lazy
Data.SequenceCons-list for queue-like operations
Data.TextString
Data.ByteStringLazy 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 centre
  • my-app.hp — heap profile (view with hp2pretty or hp2ps)

Reading the .prof file

Focus on the columns:

  • %time — fraction of time spent in this cost centre
  • %alloc — fraction of allocations attributed here
  • ticks — 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

PatternProblemFix
foldlThunk accumulation, stack overflowfoldl'
Data.List.nubO(n²)Set.toList . Set.fromList or nubOrd
++ in a loopO(n) per append, O(n²) overallData.DList or accumulate in reverse then reverse once
length on a listO(n)Keep a counter separately, or use Data.Sequence
show on large values for loggingAllocates the whole stringUse prettyprinter with lazy rendering
Lazy Text / ByteString for in-memory buffersFragmented, extra indirectionStrict Text / ByteString
String for performance-sensitive pathsLinked list of Char; slowText or ByteString
Map.insertWith on Data.Map.LazyValues not evaluated on insertData.Map.Strict
This skill doesn’t include stateful context yet, instructions only. Learn about stateful skills.

Security

Loading security scan...

Reviews (0)

More from Pragmatic Haskell

View source →

More Build skills

Browse category →
senior-frontendBuild and review React, Next.js, TypeScript or Tailwind frontends: components, scaffolding, performance and bundle size. Use whenever the user wants a new component or app, a page feels slow, the bundle is too big, or asks for a frontend code review.635 installsui-design-systemUse when building a design system: tokens, component docs, responsive scales or developer handoff. Generates tokens with design_token_generator.py.535 installsfrontend-designGuidance for distinctive, intentional visual design when building new UI or reshaping an existing one. Helps with aesthetic direction, typography, and making choices that don't read as templated defaults.346 installssenior-backendBuild and fix backend services: REST or GraphQL APIs, auth, microservices, PostgreSQL queries, migrations and load tests. Use whenever the user's API is slow or broken, needs login or auth added, a schema change, or a new endpoint or service scaffolded.246 installsself-improving-agentCurate what the agent has learned into durable project knowledge. Reviews Claude Code auto-memory (MEMORY.md and its topic files) for learnings worth keeping, promotes proven ones into CLAUDE.md or .claude/rules/, records a correction as a lesson that persists across sessions, prunes stale or duplicate entries, and turns a recurring fix into a reusable skill. Use whenever the user asks what you have learned or saved about the project, which memories should become permanent rules, to remember a lesson or stop repeating a mistake, or to clean up, audit or check memory health.173 installsusing-superpowersUse when starting any conversation - establishes how to find and use skills, requiring skill invocation before ANY response including clarifying questions145 installs

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.