Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a runtime penalty associated with typeclasses?

Tags:

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?

like image 647
Jon Smark Avatar asked Apr 13 '12 22:04

Jon Smark


People also ask

What are Typeclasses in Haskell?

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.

What is an instance of a Haskell type class?

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.

What are type classes in Haskell What purpose do they serve?

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.]


1 Answers

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.

like image 145
Edward Kmett Avatar answered Nov 28 '22 09:11

Edward Kmett