git/list[1] front-page[2] threads[3] people[4] search[5] about
 

[PATCH] lookup_object: remove hashtable_index() and optimize hash_obj()

From
Nicolas Pitre <nico@fluxnic.net>
Date
Sep 10, 2013, 22:17 UTC
Message-ID
<alpine.LFD.2.03.1309101811510.20709@syhkavp.arg>

hashtable_index() appears to be a close duplicate of hash_obj(). Keep only the later and make it usable for all cases.

Also remove the modulus as this is an expansive operation. The size argument is always a power of 2 anyway, so a simple mask operation provides the same result.

On a 'git rev-list --all --objects' run this decreased the time spent in lookup_object from 27.5% to 24.1%.

Signed-off-by: Nicolas Pitre <nico@fluxnic.net>
---
I discovered this patch in my git work tree dating from 2 years ago.
diff --git a/object.c b/object.c
index d8a4b1f..e2dae22 100644
--- a/object.c
+++ b/object.c
@@ -43,16 +43,16 @@ int type_from_string(const char *str)
 	die("invalid object type \"%s\"", str);
 }
 
-static unsigned int hash_obj(struct object *obj, unsigned int n)
+static unsigned int hash_obj(const unsigned char *sha1, unsigned int n)
 {
 	unsigned int hash;
-	memcpy(&hash, obj->sha1, sizeof(unsigned int));
-	return hash % n;
+	memcpy(&hash, sha1, sizeof(unsigned int));
+	return hash & (n - 1);
 }
 
 static void insert_obj_hash(struct object *obj, struct object **hash, unsigned int size)
 {
-	unsigned int j = hash_obj(obj, size);
+	unsigned int j = hash_obj(obj->sha1, size);
 
 	while (hash[j]) {
 		j++;
@@ -62,13 +62,6 @@ static void insert_obj_hash(struct object *obj, struct object **hash, unsigned i
 	hash[j] = obj;
 }
 
-static unsigned int hashtable_index(const unsigned char *sha1)
-{
-	unsigned int i;
-	memcpy(&i, sha1, sizeof(unsigned int));
-	return i % obj_hash_size;
-}
-
 struct object *lookup_object(const unsigned char *sha1)
 {
 	unsigned int i, first;
@@ -77,7 +70,7 @@ struct object *lookup_object(const unsigned char *sha1)
 	if (!obj_hash)
 		return NULL;
 
-	first = i = hashtable_index(sha1);
+	first = i = hash_obj(sha1, obj_hash_size);
 	while ((obj = obj_hash[i]) != NULL) {
 		if (!hashcmp(sha1, obj->sha1))
 			break;
Next: Jeff King
Message 1 of 4 in “lookup_object: remove hashtable_index() and optimize hash_obj()”
  1. lookup_object: remove hashtable_index() and optimize hash_obj()Nicolas Pitre, Sep 10, 2013
  2. Jeff KingSep 11, 2013
  3. Nicolas PitreSep 12, 2013
  4. Junio C HamanoSep 12, 2013

Read the whole thread, see it on lore, or plain text.

$ cat FOOTERMessages come from the public archive at lore.kernel.org/git, fetched every hour. The front page is chosen and written each morning by an AI editor and can be wrong; the threads themselves are the record. About and API. For agents: an MCP server at https://gitlist.dev/mcp, and any thread, story or person page as Markdown by adding .md to its URL (or sending Accept: text/markdown). Details in /llms.txt.