Skip to content

Commit

Permalink
Use quadratic probing
Browse files Browse the repository at this point in the history
This offers a small performance boost for table-heavy programs.
  • Loading branch information
darrylabbate committed Jul 30, 2021
1 parent fe5b7e2 commit ec2287a
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 12 deletions.
19 changes: 8 additions & 11 deletions src/hash.c
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,7 @@
#include "types.h"
#include "util.h"

#include <stdio.h> // Debug purposes

#define LOAD_FACTOR 0.6
#define LOAD_FACTOR 0.49

#define set(f) h->f = 1
#define unset(f) h->f = 0
Expand Down Expand Up @@ -60,8 +58,10 @@ static ht_node *new_node(rf_str *k, rf_val *v) {
static uint32_t node_slot(ht_node **e, uint32_t cap, uint32_t hash) {
cap -= 1;
uint32_t i = hash & cap;
while (e[i] && e[i]->key->hash != hash) {
i = (i + 1) & cap; // Linear probing
for (uint32_t j = 1; j <= cap; ++j) {
if (!e[i] || e[i]->key->hash == hash)
break;
i = (i + j * j) & cap;
}
return i;
}
Expand All @@ -74,14 +74,11 @@ static int exists(rf_htbl *h, rf_str *k) {
return h->nodes[i] && h->nodes[i]->key->hash == k->hash;
}

#include <inttypes.h>

int h_exists_int(rf_htbl *h, rf_int k) {
if (!h->cap) return 0;
char str[32];
size_t len = sprintf(str, "%"PRId64, k);
str[len] = '\0';
return exists(h, &(rf_str){len,u_strhash(str),str});
char str[21];
size_t len = u_int2str(k, str, sizeof str);
return exists(h, &(rf_str){len, u_strhash(str), str});
}


Expand Down
1 change: 0 additions & 1 deletion src/util.c
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
#include <ctype.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>

#include "util.h"
Expand Down
1 change: 1 addition & 0 deletions src/util.h
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

#include <inttypes.h>
#include <stdint.h>
#include <stdio.h>

#define u_int2str(i,b,n) snprintf(b, n, "%"PRId64, i)
#define u_flt2str(f,b,n) snprintf(b, n, "%g", f)
Expand Down

0 comments on commit ec2287a

Please sign in to comment.