[Haskell-cafe] looking for optimization advice

Simon Marlow simonmar at microsoft.com
Mon Mar 29 15:55:40 EST 2004

> I think that adding the extra check to see if the pointers 
> are identical
> sped this up enough that it's probably no longer a major 
> issue--I'm pretty
> certain that the problem was large strings that were 
> identical, so every
> byte had to be checked, so probably scary non-portable home-made
> ForeignPtrs would not be worth the effort.  (Although I'm 
> somewhat curious as to how it would be done...)

A ForeignPtr allocated with mallocForeignPtr in GHC is heap-allocated
garbage-collectable storage, and doesn't need a finalizer.  The other
kind of ForeignPtr created with newForeignPtr is associated with some
external storage and needs a finalizer.  Finalizers are expensive, and
so is malloc(), but mallocForeignPtr is very cheap.

This gives rise to a sum-type in the implementation of ForeignPtr: see
the source code (libraries/base/GHC/ForeignPtr.hs).  You could make a
specialised version by ripping out the non-malloc ForeignPtr bits, and
make an unboxable ForeignPtr type.

A mallocForeignPtr-style ForeignPtr is essentially the same as an
IOUArray.  In fact, the underlying implementation type is the same
(MutableByteArray#), except that a ForeignPtr is allocated in pinned
(immovable) storage so that it can be passed to foreign functions.
There could easily be a conversion from a "malloc" ForeignPtr to

There is also some overlap with the StorableArray type.  A StorableArray
has a ForeignPtr inside it.  

It really looks like the framework could be simplified here, but I
remember putting some thought into it and not coming up with a simple


More information about the Haskell-Cafe mailing list