]> granicus.if.org Git - curl/commitdiff
hash: move key into hash struct to reduce mallocs
authorDaniel Stenberg <daniel@haxx.se>
Fri, 31 Mar 2017 23:12:32 +0000 (01:12 +0200)
committerDaniel Stenberg <daniel@haxx.se>
Tue, 4 Apr 2017 13:37:37 +0000 (15:37 +0200)
This removes one tiny malloc for each hash struct allocated. In a simple
case like "curl localhost", this save three mallocs.

Closes #1376

lib/hash.c
lib/hash.h

index c76bc1d95cfd73bbe2ea8a47308fa22136d02b4b..b7305a572a882efa61b411064735a03abb686857 100644 (file)
@@ -37,8 +37,6 @@ hash_element_dtor(void *user, void *element)
   struct curl_hash *h = (struct curl_hash *) user;
   struct curl_hash_element *e = (struct curl_hash_element *) element;
 
-  Curl_safefree(e->key);
-
   if(e->ptr) {
     h->dtor(e->ptr);
     e->ptr = NULL;
@@ -87,23 +85,14 @@ Curl_hash_init(struct curl_hash *h,
 static struct curl_hash_element *
 mk_hash_element(const void *key, size_t key_len, const void *p)
 {
-  struct curl_hash_element *he = malloc(sizeof(struct curl_hash_element));
-
+  /* allocate the struct plus memory after it to store the key */
+  struct curl_hash_element *he = malloc(sizeof(struct curl_hash_element) +
+                                        key_len);
   if(he) {
-    void *dupkey = malloc(key_len);
-    if(dupkey) {
-      /* copy the key */
-      memcpy(dupkey, key, key_len);
-
-      he->key = dupkey;
-      he->key_len = key_len;
-      he->ptr = (void *) p;
-    }
-    else {
-      /* failed to duplicate the key, free memory and fail */
-      free(he);
-      he = NULL;
-    }
+    /* copy the key */
+    memcpy(he->key, key, key_len);
+    he->key_len = key_len;
+    he->ptr = (void *) p;
   }
   return he;
 }
@@ -145,7 +134,6 @@ Curl_hash_add(struct curl_hash *h, void *key, size_t key_len, void *p)
      * "destructor" for the actual data 'p'. When we fail, we shall not touch
      * that data.
      */
-    free(he->key);
     free(he);
   }
 
index 5929fc2648c65fbb21c0d80fd92e946a0fc5c36d..a345c8c87ef7419a11aa9cdc446964cbed35afa3 100644 (file)
@@ -58,8 +58,8 @@ struct curl_hash {
 
 struct curl_hash_element {
   void   *ptr;
-  char   *key;
   size_t key_len;
+  char   key[1]; /* allocated memory following the struct */
 };
 
 struct curl_hash_iterator {