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?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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.