Skip to content

Commit 3fb9d68

Browse files
committed
Merge branch 'np/lookup-object-hashing'
Micro optimize hash function used in the object hash table. * np/lookup-object-hashing: lookup_object: remove hashtable_index() and optimize hash_obj()
2 parents 0809208 + 9f36c9b commit 3fb9d68

File tree

1 file changed

+10
-12
lines changed

1 file changed

+10
-12
lines changed

object.c

Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -43,16 +43,17 @@ int type_from_string(const char *str)
4343
die("invalid object type \"%s\"", str);
4444
}
4545

46-
static unsigned int hash_obj(struct object *obj, unsigned int n)
46+
static unsigned int hash_obj(const unsigned char *sha1, unsigned int n)
4747
{
4848
unsigned int hash;
49-
memcpy(&hash, obj->sha1, sizeof(unsigned int));
50-
return hash % n;
49+
memcpy(&hash, sha1, sizeof(unsigned int));
50+
/* Assumes power-of-2 hash sizes in grow_object_hash */
51+
return hash & (n - 1);
5152
}
5253

5354
static void insert_obj_hash(struct object *obj, struct object **hash, unsigned int size)
5455
{
55-
unsigned int j = hash_obj(obj, size);
56+
unsigned int j = hash_obj(obj->sha1, size);
5657

5758
while (hash[j]) {
5859
j++;
@@ -62,13 +63,6 @@ static void insert_obj_hash(struct object *obj, struct object **hash, unsigned i
6263
hash[j] = obj;
6364
}
6465

65-
static unsigned int hashtable_index(const unsigned char *sha1)
66-
{
67-
unsigned int i;
68-
memcpy(&i, sha1, sizeof(unsigned int));
69-
return i % obj_hash_size;
70-
}
71-
7266
struct object *lookup_object(const unsigned char *sha1)
7367
{
7468
unsigned int i, first;
@@ -77,7 +71,7 @@ struct object *lookup_object(const unsigned char *sha1)
7771
if (!obj_hash)
7872
return NULL;
7973

80-
first = i = hashtable_index(sha1);
74+
first = i = hash_obj(sha1, obj_hash_size);
8175
while ((obj = obj_hash[i]) != NULL) {
8276
if (!hashcmp(sha1, obj->sha1))
8377
break;
@@ -101,6 +95,10 @@ struct object *lookup_object(const unsigned char *sha1)
10195
static void grow_object_hash(void)
10296
{
10397
int i;
98+
/*
99+
* Note that this size must always be power-of-2 to match hash_obj
100+
* above.
101+
*/
104102
int new_hash_size = obj_hash_size < 32 ? 32 : 2 * obj_hash_size;
105103
struct object **new_hash;
106104

0 commit comments

Comments
 (0)