Performance-loss of accessing data through class?
simonmar at microsoft.com
Mon Oct 11 07:26:53 EDT 2004
On 10 October 2004 02:01, Peter Simons wrote:
> in a module I am writing, I am using a 'StateT st IO' monad
> with a state like this:
> data MyState st = ST !Int !st
> My own monad is yet-another wrapper for ... another state
> monad. And that's getting inconvenient.
> So I wondered whether it would be good to define a class
> that unified all those StateTs into _one_ state, like:
>> class KnowsMyStuff a where
>> foo :: a -> Int
>> bar :: a -> Float
>> etc :: a -> [String]
> Then I could write my functions so that they'd work on any
> MonadIO which has some way of getting those instances
> If I did that, how much performance would I lose? Accessing
> those values would probably require one more level of
> indirection, that can't be as fast as having a specific data
> type, right?
> Or is there some optimizer magic at work here?
If your code is using a method from a known instance of a class, and the
method has a small enough definition, then chances are good that it'll
get inlined and the extra layer of abstraction will dissappear. I'm
guessing this is the case with your example.
If performance is important, then you should probably check the
simplifier output with -ddump-simpl to make sure that the code is what
We always enjoy investigating benchmarks, so if you have some code you
think isn't going fast enough, then post it here and we'll help you find
out where the performance problems are.
More information about the Glasgow-haskell-users