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?
What's a typeclass in Haskell? A typeclass defines a set of methods that is shared across multiple types. For a type to belong to a typeclass, it needs to implement the methods of that typeclass. These implementations are ad-hoc: methods can have different implementations for different types.
An instance of a class is an individual object which belongs to that class. In Haskell, the class system is (roughly speaking) a way to group similar types. (This is the reason we call them "type classes"). An instance of a class is an individual type which belongs to that class.
In Haskell, type classes provide a structured way to control ad hoc polymorphism, or overloading. [For the stylistic reason we discussed in Section 3.1, we have chosen to define elem in infix form. == and || are the infix operators for equality and logical or, respectively.]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With