Fergus Henderson fjh at cs.mu.oz.au
Mon Dec 4 19:59:46 EST 2000

On 04-Dec-2000, Marcin 'Qrczak' Kowalczyk <qrczak at knm.org.pl> wrote:
> Mon, 4 Dec 2000 04:15:28 -0800, Simon Marlow <simonmar at microsoft.com> pisze:
> > Ok, so the malloc/free is the most expensive part.  I'm moderately
> > surprised:)  Perhaps we could do a better job, but we'll never do
> > better than ByteArrays as long as the bracket is required.
> BTW, withCString in my implementation which handles charsets does not
> use alloca but malloc. It's because we don't know the length of the
> resulting char[] until we convert it, so we cannot preallocate it.
> We must guess an initial size and realloc the array as needed.

I don't know the details of withCString, so this might not be
applicable, but an alternative that is likely to be more efficient is
to use a static or alloca()'ed buffer for the initial try, and if it
doesn't fit then switch to using malloc()/realloc().
At the end, you can check whether the final buffer pointer is equal to
the original fixed-size static or alloca()'ed buffer, and only free it
if it is not.  Or you can keep a separate boolean flag.

Fergus Henderson <fjh at cs.mu.oz.au>  |  "I have always known that the pursuit
                                    |  of excellence is a lethal habit"
WWW: <http://www.cs.mu.oz.au/~fjh>  |     -- the last words of T. S. Garp.

More information about the FFI mailing list