Jon Smark
Jon Smark

Reputation: 2608

Is there a runtime penalty associated with typeclasses?

The title pretty much sums up my question: is there a runtime penalty associated with Haskell's typeclasses, or is it just one of those things (like phantom types) with no runtime consequence whatsoever?

Upvotes: 21

Views: 866

Answers (1)

Edward Kmett
Edward Kmett

Reputation: 29962

Requiring a typeclass is just like passing an extra argument to the function containing the members of the type class as a data structure, since behind the scenes that is what it desugars into in GHC.

That said, GHC is pretty good at inlining and specializing away code that uses typeclasses to the point where its not a problem, with -O2 a very large percentage of them just disappear, but even without that kind of optimization level passing arguments is pretty cheap.

So the overhead is more than a phantom type or newtype, but it isn't very high.

As an aside, the overhead in other compilers can vary. e.g. JHC effectively performs case analysis on the type constructors using a limited form of dependent types, so you pay for the number of constrained type variables, not the number of constraints when working in JHC.

Upvotes: 17

Related Questions