Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

type vs data performance in haskell

Tags:

types

haskell

I found answers explaining difference between newtype and data in Haskell. But if I have the following type synonym:

type Point = (Int,Int)

Would that be more efficient rather to use:

data Point = Pt (Int,Int) ?
like image 208
vis Avatar asked Jun 08 '11 10:06

vis


People also ask

What is the difference between type and data in Haskell?

Type and data type refer to exactly the same concept. The Haskell keywords type and data are different, though: data allows you to introduce a new algebraic data type, while type just makes a type synonym. See the Haskell wiki for details.

What does type do in Haskell?

In Haskell, types are how you describe the data your program will work with.

What is the difference between type and data type?

As data type already represents the type of value that can be stored so values can directly be assigned to the data type variables. On other hand in case of data structure the data is assigned to using some set of algorithms and operations like push, pop and so on.

Is Haskell strict?

Haskell is a non-strict language, and most implementations use a strategy called laziness to run your program.


2 Answers

Using type will be more efficient, as it incurs one less indirection than the data version.

Note that both are more inefficient than:

data Point = Point {-# UNPACK #-}!Int {-# UNPACK #-}!Int

as you can see from this earlier question on data representations.

like image 197
Don Stewart Avatar answered Nov 15 '22 09:11

Don Stewart


Yes.

The Pt construction adds one word of overhead (in GHC) and the field (i.e. the pair) is stored as a pointer to a pair, adding one additional word, for a total of two words overhead (and an extra indirection to get to the values).

I recommend that you either use the type synonym or, better yet, define

data Point = Pt {-# UNPACK #-} !Int {-# UNPACK #-} !Int

This requires 4 words less than

type Point = (Int, Int)

and uses one less level of indirections (pointers).

like image 41
tibbe Avatar answered Nov 15 '22 11:11

tibbe