13 ms·
Implementing Hash Tables in C
- ufo 5y ago> The % operation is quite efficient (although it’s usually two times more expensive than multiplication); I though it was much more than two times slower? Division and modulus are the slowest integer operation.
- veltas 5y agoIt makes a significant difference in profiling, versus i.e. a bitwise mask to find a modulus for a power-of-two size.
- pansa2 5y agoAgner Fog’s manual lists a latency/reciprocal-throughput of 15/10 for 64-bit divide on Ivy Lake & Tiger Lake, vs 3/1 for 64-bit multiply. So division is 5-10x slower than multiplication. https://www.agner.org/optimize/#manuals https://www.agner.org/optimize/#manuals
- FullyFunctional 5y agoI had hoped for a little more insight and information density, but I did learn about Knuth's hash x(x+3) % P which was news to me. However these are all techniques that I might have used in undergrad, but today I would hands down use Cuckoo hashing unless the application domain was insertion dominated.
- racl101 5y agoWow, learned more from this than from Uni.
- kevin_thibedeau 5y ago> In modern times, modern compilers can perform all kinds of optimizations, including this one. So it’s up to you to decide if making things harder to read is worth it. It is still worthwhile to manually perform these arithmetic optimizations because you may want to build with optimizations off and switching to actual multiplication in hot code paths can cause performance regressions. An unrelated area where I wouldn't do this sort of thing is bit twiddling tricks to implement branchless code. That generally defeats modern compilers' abilities to generate branchless code with conditional moves and ends up being slower.
- chrisseaton 5y ago> switching to actual multiplication in hot code paths can cause performance regressions Why would you turn off optimisations if you were worried about performance optimisations?
- matheusmoreira 5y agoSometimes the compilers will do insane stuff that causes bugs if you enable too much optimization. Usually because of strict aliasing violations causing undefined behavior.
- kroltan 5y ago...don't violate strict aliasing then?
- matheusmoreira 5y agoAliasing is ubiquitous in systems programming. Reinterpreting arbitrary types as arrays of bytes, for example. Honestly, it's kind of amazing that C even has this rule. Seems to be an attempt to be competitive with Fortran.
- eperdew 5y agoThis is why the aliasing rules in C explicitly allow aliasing any pointer type with a char*.
- matheusmoreira 5y agoYeah, but char sucks. It's not a synonym for octet. Not guaranteed to be 8 bits. Its signedness is even ambiguous unless unsigned is specified. The correct type is uint8_t/u8. Sadly, using that to alias other types is undefined. I've also seen hashing algorithms which used uint16_t/u16, with similar aliasing optimization bugs. Sometimes you want to reinterpret things as a struct, too. This is the reason why Linux compiles with strict aliasing disabled.
- gautamcgoel 5y agoThe I believe that author gets the value of phi wrong: it is roughly 1.618, not 0.618.
- Bootvis 5y agoHe probably confused it with 1/phi and didn’t check his equation.
- kangalioo 5y agoTIL 1/phi=phi-1
- messe 5y agoThat's essentially the definition. φ is the solution to φ^2 - φ - 1 = 0 Which can be re-arranged, by dividing by φ to, φ - 1 - 1/φ = 0 or: 1/φ = φ - 1
- marginalia_nu 5y agoOr φ^-1=φ-1
- messe 5y agoYes, φ^-1 is another way to write 1/φ.
- marginalia_nu 5y agoYeah but the 【 aesthetics】
- klyrs 5y agoHappy phi day ^_^
- lmkg 5y agoSeveral ways of defining the Golden Ratio allow either, or both. One convention is that upper-case Phi or Φ is 1.618[...], while lower-case phi or φ is 0.618[...]. The values are related by φ = 1/Φ, as well as Φ = φ + 1. Both of these relations can be derived from the fact that they are the ratios of a Golden Rectangle--if a square has length one, then adding a rectangle with height φ to the side will give a rectangle of length Φ, and the rectangles are Similar.
- olav 5y agoNice article. Since the beginning of the 1990s I enjoy using the hash tables implemented by John Ousterhout for Tcl: https://core.tcl-lang.org/tcl/file?name=generic/tclHash.c&ci=tip https://core.tcl-lang.org/tcl/file?name=generic/tclHash.c&ci...
- SavantIdiot 5y agoSimilarly, Robert Sedgewick covered this in his 1990's book "Algorithms in C" quite nicely, and a bit more succinctly, IMO. https://www.amazon.com/Algorithms-Computer-Science-Robert-Sedgewick/dp/0201514257 https://www.amazon.com/Algorithms-Computer-Science-Robert-Se...
- chrisseaton 5y agoWhen I was an undergraduate my university used a test of ‘can you implement a hash table in C’ as their basic ‘can you really program’ test to stream incoming students.
- whimsicalism 5y agoI think I'd have trouble with the hashing function but unless you're using a basic modulo.
- cle 5y agoIMO this is the least interesting part of a question like "can you write a hash table", unless you're in an area where writing hash functions is a critical skill. You have to deal with collisions either way...the ideal solution for me testing someone's software engineering skills would be one that uses a crappy hash function, but can trivially swap it out for something better. (Maybe this is different than what a school is testing for though?)
- vidarh 5y agoI agree. If I gave a test like that and someone gave me an answer where the hash function was pretty much just a dummy I'd be fine with that as long as they were clearly aware it was just a dummy and hopefully could explain roughly the characteristics of a good hash function.
- DudeInBasement 5y agosearch_index = value & ((hash_length_power_of2) - 1)
- Swizec 5y agoBack then that was likely true. Just like building linked lists from scratch was on the same level as writing a basic loop nowadays High level programming languages have come a long way in the past 20 years. So many things we no longer need to think about in normal day to day programming
- armeehn 5y agoUnless I'm missing something, the definition of H_division is misleading. The co-domain (image) set is really {0, ..., M - 1}, which _is_ surely a subset of [0, M), although definitely very different in size. Usually it's written as Z/qZ where q = M. Neat article otherwise. It reminded me of mappings to real numbers which I always found interesting during my undergrad.
- ternaryoperator 5y agoHe seems to overlook a fundamental optimization for open hash tables: ordering the elements in the linked list associated with each bucket. Right now to find an element, he reads the entire linked list if it's not there. By ordering the elements in the list upon insertion, he can greatly improve on that.
- Delk 5y agoWouldn't ordering basically improve lookup performance at the expense of insertion performance? If you don't order the elements, you can just smash the new entry at the end of the list and be done with it. Of course that might still be a reasonable trade-off to make. Is there experimental (or experiential) support for getting significant improvements from ordering?
- ternaryoperator 5y agoMany (most?) hash tables are write-once, read-many (caches, databases, etc. among others) so optimizing for reading makes a lot of sense.
- hawk_ 5y agoordered insertion can happen in the "middle" of the list. unordered always has to reach the end (to ensure no duplicate) so it's worse for insertion as well.
- Delk 5y agoGood point. For some reason I didn't think about duplicate checking even though it's pretty obvious.
- sltkr 5y agoThis is possible, but typically this is not done for generic hash tables because it requires keys to be ordered (i.e. there must be a function that can tell whether one key is less than, greater than, or equal to another) while the current implementation only requires testing for equality.
- rdpintqogeogsaa 5y agoNote that if you have untrusted input, you may want to use a defensive option for hashing involving a private key, such as SipHash[1]. Otherwise, an attacker who knows your hash functions can just pre-generate a large number of colliding elements and reduce your hash function to a linked list; given enough attacker-controlled elements, this can effectively amount to a DoS attack[2]. [1] https://github.com/veorq/SipHash https://github.com/veorq/SipHash [2] https://www.aumasson.jp/siphash/siphashdos_29c3_slides.pdf https://www.aumasson.jp/siphash/siphashdos_29c3_slides.pdf
- pansa2 5y agoSipHash is considerably slower than an unkeyed hash function, isn’t it? One idea I had to avoid its overhead is to use double hashing, with a fast primary hash and SipHash as the secondary hash. Naïvely this feels as though it should provide good performance in the common case and also good security - even if there are many primary hash collisions, they won’t also be secondary hash collisions. Does anyone know if there is an analysis of this approach anywhere?
- veltas 5y agoAnother alternative is not using a hash table, and instead using a sorted binary tree or similar, which tends to be slower on average but has worst case O(log n) lookup, O(log n) insertion. Depends on your criteria.
- dhosek 5y agoThat depends on the implementation. If it's a simple binary tree, the worst case is O(n), not O(log n) since if you insert data in sorted order everything will always be in the left branch. O(log n) is average lookup time. If you have a specialized tree structure like a red-black tree which will automatically balance, this will improve, but sorted input is still a viable attack method. That said, a lot depends on the application and one should pick a hash function wisely. A binary tree–mapped hash table works best when you want to be able to iterate on keys in sort order or find an entry that's just before or just after a non-existent key in sort order. It's not really a good defense against hash attacks. On the flip side, the default hasher in Rust is hardened against hash attacks, but it's overkill for most applications and can cause severe performance degradation (although at least the library documentation is clear on this and points at alternative hash implementations for such cases). Unfortunately, the Rust resizing algorithm is flawed and won't resize until the hash capacity is completely full¹ making hash collisions much more likely. I had a doubling of performance in benchmarking some code that I was writing just by increasing the initial capacity of the map. ⸻⸻⸻ 1. A common mistake I see Java developers make is, when they know they'll be inserting n items into a HashSet or HashMap is to initialize the structure with a capacity of n. This guarantees that Java will end up re-allocating the index since the default load factor in Java is 0.55 meaning that once you have 0.55×capacity elements in your collection it will resize.
- quotemstr 5y agoGreat article --- very little having to do with C though. It might be unpopular to say this but: can we please stop teaching people to write new programs in C? The language is inherently unsafe, and we're collectively losing billions of dollars per year to preventable memory safety errors. Why not use Rust or C# or something to demonstrate the principles of hash tables? Why start with the programming equivalent of a 1950s death crap automobile with a spike in the center of the steering wheel?
- smackeyacky 5y agoOut in embedded land, where you will have C, assembler and a tiny library if you are lucky, the luxuries of Rust just aren't widely available yet. Its also a very valuable language to learn since the big 3 operating systems are made out of it. You can't wish that away.
- glowmeg 5y agoOut of curiosity, what kind of embedded device has only C and asm support? Usually, the compiler used for these is gcc which, for a really long time is written in C++. It shouldn't be hard to use even go on embedded now. Also Rust gets rustc_codegen_gcc[1], so you will be able to use it everywhere. [1] https://github.com/rust-lang/rust/tree/master/compiler/rustc_codegen_gcc https://github.com/rust-lang/rust/tree/master/compiler/rustc...
- pjc50 5y agoPIC16?
- smackeyacky 5y agoSometimes the compiler is gcc, but the libraries are...some weird hybrid. Texas Instruments RTOS used their own compiler and a strange mashup of C/C++ (xdctools they call it). I don't understand it, it kind of looks like if somebody had been described the original cfront over the telephone. The latest versions are undoing some of that and they even have the option of using a clang compiler, but on their older chips you are stuck with the original weirdness, which basically means you are restricted to C and assembly in a practical sense.
- veltas 5y agoOpen addressing or 'open bucket' hash tables always seem to be a second consideration in textbooks or blogs. I find them generally faster, and more memory efficient, and easier to implement. Instead we're always taught the closed bucket approach, often using linked list buckets of all things. In certain scenarios open addressing has worse performance, but with the right optimisations it's generally only contrived situations where it performs worse. In normal usage, open addressing has vastly superior locality, a smaller memory footprint, and less dereferencing overhead. A lot of writing and textbooks describing open addressing seem to imply that the order of walking through the table when collisions occur is really important (and it is). But the approach with best performance in practice is to just do a dumb increment through the table in-order because of caching... the penalty for that simple approach can be made up for with a good, pseudo-random hash.
- jhgb 5y ago> Open addressing or 'open bucket' hash tables always seem to be a second consideration in textbooks or blogs. I find that weird since my introductory textbook went straight for an open addressing, linear probing hash table -- probably because this approach is ancient. I'm not even sure a different approach was mentioned (but of course in that course, it was only one topic out of many to grasp).
- evouga 5y agoI’m missing something… doesn’t open addressing fail catastrophically the moment you try to insert more items than the table has buckets? (With very bad degradation in performance as you approach this saturation point)? Is the idea that you only use open addressing in cases where you know you’ll place much fewer items into the table than the number of bins?
- gdwatson 5y agoWhen the load factor of an open-addressed hashtable gets too high, you allocate a larger set of buckets and rehash the table’s existing contents into them. You’ll have to do this with a chained hashtable anyway, as performance will start to approach O(n) once the table is overloaded. This does mean that insertion time goes from a true O(1) to an amortized O(1), but that’s usually not an issue. (You can do the rehashing gradually if you really have to, but it’s probably not worth the complexity.)
- scandox 5y ago> Cryptographic hash functions are a special family of hash functions. For security considerations, they exhibit an extra set of properties. The functions used in hash table implementations are significantly less pretentious.
- rurban 5y agoSpare this light article on bad hash tables. The best one in C is currently github.com/LIMachi/swiss-table but this is missing the security discussion.
- ufo 5y agoI wish this article was more opinionated. One of my pet peeves about hash tables is that most of the resources about it describe how there are dozens of different ways to do it (different hash functions, different collision management, etc), but they often don't tell you which one you should choose.
- csydas 5y agoAs a nascent dev, at least the best advice I've gotten so far was "write what is necessary for you". There are obvious "bad" practices that need to be eliminated early on to make life easier, but for something like this I think the wisdom is more just work with it yourself and find what does or does not work and why. My biggest "leaps" have been to spend time on code and get the general system I need in place and working, then consult with a more senior colleague on it. Typically, once I've gotten my work to a point where the intended system is clear enough and I have functional code, that's where a more senior review can first take place and: 1. The senior can immediately (hopefully) understand what our goal is here 2. The senior likely has some ideas on better ways to approach it than I did in the first iteration 3. If it does get to matters of opinion, at least I'm lucky enough that my senior is very unemotional about such things and explains why they like their way, but usually can understand why I did something the way I did And after that, I iterate and I feel like I get the idea way better. Trying to think about the "right way" from the beginning traps me a lot personally and almost scares me that I'm going to do something wrong. I also don't really feel I "get" why something is the right way until I've done it the wrong way or at least explored the wrong way a bit first. But again, I'm pretty nascent so you might be talking on a different level. But I feel this experience applies to basically everything with code, and just getting your hands into bad implementations and being willing to rewrite is the best way to find that "right" way for you.
- nomemory 5y agoI don't think there's consensus and very few people have a total grasp of the subject. Look Java and python for example. The people working on the languages are quite smart, and they decided to take different routes. Who was right ?
- ZoomZoomZoom 5y ago
- RustyRussell 5y agoCCAN's htable uses open addressing, and bit stealing from the pointers for maximal density (extra hash bits go here to avoid derefs for misses). The result is that performance tends to be great up to about 95% full. The resize operation is a dumb double-and-rehash, but for most programs, the lower cache impact is a win.
- throwaway201025 5y agoSamsung has an internal programming test for its employees, and it prevents the use of any standard libraries. So we have to implement hash tables ourselves every time. It is good that I now find it relatively easy to build hash tables myself, but I think this limitation is too restrictive because being good at implementing hash tables hasn't been useful to my daily programming tasks.
- tantalor 5y agoWhat is the test required for?
- govg 5y agoFor what it's worth, their recruitment tests for fresh graduates in India is similar in that it doesn't allow usage of any STL. At least, that was the case 3 years or so ago.
- throwaway201025 5y agoIt must be the same test. There are three levels in the test and new employees are given the first level. Just out of curiosity, did you take the exam? Was the process satisfactory? Did you have a feeling that the test correctly represented participants' skills?
- throwaway201025 5y agoIt is not exactly mandatory, but the company nags the employees who haven't passed the exam yet. It is also good for your performance rating, because the managers are advised to consider the result of the exam when doing performance review.
- joppy 5y agoJavaScript is a language where you need to implement your own hash table, since the built-in object only understands key strings, and the built-in Map class only has value semantics when the keys are primitive types (strings, ints, etc), and compares objects by object identity.