Looking for a good hash table implementation in C

Setjmp picture Setjmp · Jul 16, 2009 · Viewed 75k times · Source

I am primarily interested in string keys. Can someone point me towards a library?

Answer

Karthik Gurusamy picture Karthik Gurusamy · Dec 12, 2011

I had the same need and did some research and ended up using libcfu

It's simple and readable so if I have a need to modify, I can do it without spending too much time to understand. It's also of BSD license. No need to change my structs (to embed say a next pointer)

I had to reject the other options for following reasons (my personal reasons, YMMV):

  • sglib --> it's a macro maze and I wasn't comfortable debugging/making changes on such a code base using just macros
  • cbfalconer --> lot of licensing redflags, and the site was down and too many unfavorable discussions on web about support/author; didn't want to take the risk
  • google sparce-hash --> as stated already, it's for C++, not C
  • glib (gnome hash) --> looked very promising; but I couldn't find any easy way to install the developer kit; I just needed the C routines/files -- not the full blown developement environment
  • Judy --> seems too complex for a simple use.. also was not ready to debug myself if I had to run into any issues
  • npsml (mentioned here) --> can't find the source
  • strmap found very simple and useful -- it's just too simplistic that both key and value must be strings; value being string seems too restrictive (should accept void *)
  • uthash --> seems good (has been mentioned on wikipedia on hashtable); found that it requires struct to be modified -- didn't want to do that as performace is not really a concern for my use --it's more of development velocity.

In summary for very simple use strmap is good; uthash if you are concerned with additional memory use. If just speed of development or ease of use is primary objective, libcfu wins [note libcfu internally does memory allocation to maintain the nodes/hashtables]. It's surprising that there aren't many simple C hash implementations available.