Efficient overload in Haskell

I wonder which of the two strategies below is most effective for function overloading (here the teX function in my example).

  • Using data and pattern matching:

     data TeX = TeXt String | TeXmath String deriving (Show,Read,Eq) teX (TeXt t) = t teX (TeXmath t) = "$$" ++ t ++ "$$" 
  • Or using a bit of abstraction:

     class TeX t where teX :: t -> String newtype TeXt = TeXt String deriving (Show,Read,Eq) instance TeX TeXt where teX (TeXt t) = t newtype TeXmath = TeXmath String deriving (Show,Read,Eq) instance TeX TeXmath where teX (TeXmath t) = "$$" ++ t ++ "$$" 

Of course, the first is easier to use, and the second is easier to enrich; but I wonder if it will work faster than the other, or if Haskell will implement them in exactly the same way.

+6
source share
1 answer

The first of them is more effective in space. Calling a function defined in a type class is equivalent to calling a method in an object-oriented language: any functions that are polymorphic in type TeX t (i.e., have TeX t => in the type signature) will have to carry an additional, implicit parameter, namely, a dictionary storing specific methods for a given TeX instance.

Now, faster? I would suggest that for programs with a small amount of memory, the first method is slightly faster due to less memory allocation and even less indirectness for actually calling the TeX function. For programs with intensive distribution, the same will be done until the program overcomes some threshold of mdash memory allocation, which the first version will hit later, and therefore will be somewhat faster when the second gets to this point.

+5
source

Source: https://habr.com/ru/post/943792/


All Articles