What is the most efficient way to check if two hashes h1
and h2
have the same set of keys disregarding the order? Could it be made faster or more concise with close efficiency than the answer that I post?
相关问题
- facebook error invalid key hash for some devices
- How to specify memcache server to Rack::Session::M
- Why am I getting a “C compiler cannot create execu
- reference to a method?
- ruby 1.9 wrong file encoding on windows
相关文章
- Ruby using wrong version of openssl
- Difference between Thread#run and Thread#wakeup?
- how to call a active record named scope with a str
- “No explicit conversion of Symbol into String” for
- Segmentation fault with ruby 2.0.0p247 leading to
- How to detect if an element exists in Watir
- Bcrypt vs Hash in laravel
- uninitialized constant Mysql2::Client::SECURE_CONN
Here is my solution:
Just for the sake of having at least a benchmark on this question...
Results are:
I have to agree with @akuhn that this would be a better benchmark if we had more information on the dataset you are using. But that being said, I believe this question really needed some hard fact.
Try:
Enumerable#all?
worse case scenario, you'd only be iterating through the keys once.
Combining freemasonjson's and sawa's ideas:
It depends on your data.
There is no general case really. For example, generally retrieving the entire keyset at once is faster than checking inclusion of each key seperately. However, if in your dataset, the keysets differ more often than not, then a slower solution which fails faster might be faster. For example:
Another factor to consider is the size of your hashes. If they are big a solution with higher setup cost, like calling
Set.new
, might pay off, if however they are small, it won't:And if you happen to compare the same immutable hashes over and over again, it would definitely pay off to cache the results.
Eventually only a benchmark will tell, but, to write a benchmark, we'd need to know more about your use case. For sure, testing a solution with synthetic data (as for example, randomly generated keys) will not be representative.
Alright, let's break all rules of savoir vivre and portability. MRI's C API comes into play.
Here's a Makefile.
An artificial, synthetic and simplistic benchmark shows what follows.