Re: [PATCH] ALSA: Remove subsystem-specific malloc (1/8)

Dave Jones
2004-06-10T12:33:52Z

On Wed, Jun 09, 2004 at 10:08:34PM -0700, dean gaudet wrote:

> > +void *kcalloc(size_t n, size_t size, int flags)
> > +{
> > + if (n != 0 && size > INT_MAX / n)
> > + return NULL;
>
> division isn't very efficient :) it's typically a 40+ cycle operation.
>
> there's almost certainly more efficient ways to do this with per-target
> assembly... but you should probably just crib the code from glibc which
> avoids division for small allocations:
>
> /* size_t is unsigned so the behavior on overflow is defined. */
> bytes = n * elem_size;
> #define HALF_INTERNAL_SIZE_T \
> (((INTERNAL_SIZE_T) 1) << (8 * sizeof (INTERNAL_SIZE_T) / 2))
> if (__builtin_expect ((n | elem_size) >= HALF_INTERNAL_SIZE_T, 0)) {
> if (elem_size != 0 && bytes / elem_size != n) {
> MALLOC_FAILURE_ACTION;
> return 0;
> }
> }

Considering this isn't exactly a cycle-critical piece of code,
I'd choose readability over saving 40 cycles which is probably
lost in the noise of every other operation we do in that allocation.

Dave