[[project @ 2003-03-11 10:34:58 by simonmar]
simonmar**20030311103458
- Remove mention of MutableByteArray and ByteArray
- Add section on memory allocation in the FFI, with emphasis on how
GHC's implementations of the various kinds of allocation perform.
] {
hunk ./ghc/docs/users_guide/ffi-chap.sgml 44
-
- Arrays
-
- The types ByteArray and
- MutableByteArray may be used as basic foreign types
- (see FFI Addendum, Section 3.2). In C land, they map to
- (char *).
-
-
hunk ./ghc/docs/users_guide/ffi-chap.sgml 300
+
+
+ Memory Allocation
+
+ The FFI libraries provide several ways to allocate memory
+ for use with the FFI, and it isn't always clear which way is the
+ best. This decision may be affected by how efficient a
+ particular kind of allocation is on a given compiler/platform,
+ so this section aims to shed some light on how the different
+ kinds of allocation perform with GHC.
+
+
+
+ alloca and friends
+
+ Useful for short-term allocation when the allocation
+ is intended to scope over a given IO
+ compuatation. This kind of allocation is commonly used
+ when marshalling data to and from FFI functions.
+
+ In GHC, alloca is implemented
+ using MutableByteArray#, so allocation
+ and deallocation are fast: much faster than C's
+ malloc/free, but not quite as fast as
+ stack allocation in C. Use alloca
+ whenever you can.
+
+
+
+
+ mallocForeignPtr
+
+ Useful for longer-term allocation which requires
+ garbage collection. If you intend to store the pointer to
+ the memory in a foreign data structure, then
+ mallocForeignPtr is
+ not a good choice, however.
+
+ In GHC, mallocForeignPtr is also
+ implemented using MutableByteArray#.
+ Although the memory is pointed to by a
+ ForeignPtr, there are no actual
+ finalizers involved (unless you add one with
+ addForeignPtrFinalizer), and the
+ deallocation is done using GC, so
+ mallocForeignPtr is normally very
+ cheap.
+
+
+
+
+ malloc/free
+
+ If all else fails, then you need to resort to
+ Foreign.malloc and
+ Foreign.free. These are just wrappers
+ around the C funcitons of the same name, and their
+ efficiency will depend ultimately on the implementations
+ of these functions in your platform's C library. We
+ usually find malloc and
+ free to be significantly slower than
+ the other forms of allocation above.
+
+
+
+
+ Foreign.Marhsal.Pool
+
+ Pools are currently implemented using
+ malloc/free, so while they might be a
+ more convenient way to structure your memory allocation
+ than using one of the other forms of allocation, they
+ won't be any more efficient. We do plan to provide an
+ improved-performance implementaiton of Pools in the
+ future, however.
+
+
+
+
}