Trident D'Gao
Trident D'Gao

Reputation: 19690

What brings a bigger performance hit: currying or typeclasses?

I am debating whether I should use typeclasses or just create partial applications with all necessary functions curried in.

processWith validate accept reject x xs = if validate x then accept x xs else reject x xs
process = processWith (> 0) (\x xs -> x:xs) (\x _ -> error "Unexpected x: " ++ show x)

As far as I understand conceptually it's just a matter of personal taste which way to go. Now I am wondering about the performance implications of using currying over typeclasses.

Upvotes: 0

Views: 565

Answers (1)

leftaroundabout
leftaroundabout

Reputation: 120711

Well, the crucial difference: with type classes you'll generally achieve more concise code whereas the explicit dictionary functions are more flexible.

But you can't say either is more performant. In general, type classes are simply implemented as an implicit dictionary argument, so basically syntactic sugar for your second alternative. In performance-critical cases, GHC should often be able to inline any extra calls, then neither way really as a "performance hit" at all. The good thing about type classes is that you can use {-# SPECIALISE instance #-} pragmas to help this inlining in quite an easy way; doing that with explicitly-passed dictionaries using {-# INLINABLE #-} tends to be rather more cumbersome. But then, again explicit is more general so you may find it easier to optimise a particular call with a priori unforseen combinations.

Conclusion: the best thing probably is to privide both, a version with dictionary argument and a typeclass-method equivalent. This is also done for many standard library routines.

Upvotes: 5

Related Questions