This is the mail archive of the libc-hacker@sources.redhat.com mailing list for the glibc project.

Note that libc-hacker is a closed list. You may look at the archives of this list, but subscription and posting are not open.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

[PATCH] optimize calloc


On Fri, Aug 02, 2002 at 12:13:21PM -0000, Wolfram Gloger wrote:
> > Why not 2^32? size_t is unsigned.
> 
> Yes, however malloc can only handle chunks of a little less than 2^31
> currently, so the _int_malloc later will fail anyway...  But that is
> ok, having a power of two as the compared value wins against this
> micro-optimisation:
> 
> > So you mean something like:
> >   bytes = n * elem_size;
> >   if (__builtin_expect ((a | b) >= 65536, 0)) {
> >     if (bytes / elem_size != n) {
> >       MALLOC_FAILURE_ACTION;
> >       return 0;
> >     }
> >   }
> 
> Hey, nice, avoids the second comparision and ||.  Looks like we have a
> winner?

Ok, here is the patch:

2002-08-03  Jakub Jelinek  <jakub@redhat.com>

	* malloc/malloc.c (public_cALLOc): Only divide if one of arguments
	is bigger than 65535.

--- libc/malloc/malloc.c.jj	2002-08-02 11:47:41.000000000 +0200
+++ libc/malloc/malloc.c	2002-08-03 13:47:50.000000000 +0200
@@ -488,6 +488,9 @@ Void_t *(*__morecore)(ptrdiff_t) = __def
 #endif /* _LIBC */
 #endif /* USE_DL_PREFIX */
 
+#ifndef _LIBC
+#define __builtin_expect(expr, val)	(expr)
+#endif
 
 /*
   HAVE_MEMCPY should be defined if you are not otherwise using
@@ -3466,9 +3469,11 @@ public_cALLOc(size_t n, size_t elem_size
 
   /* size_t is unsigned so the behavior on overflow is defined.  */
   bytes = n * elem_size;
-  if (bytes / elem_size != n) {
-    MALLOC_FAILURE_ACTION;
-    return 0;
+  if (__builtin_expect ((n | elem_size) >= 65536, 0)) {
+    if (bytes / elem_size != n) {
+      MALLOC_FAILURE_ACTION;
+      return 0;
+    }
   }
 
   if (hook != NULL) {


	Jakub


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]