Repository navigation
Description
@k0kubun has recently taken the time to gather some stats about the most common C and Ruby method calls in our headline benchmarks: ruby/ruby-bench#163
One of the things that is somewhat surprising is that Hash#[] is the most frequently called C method, and often by a long shot. For example, in activerecord, it makes up over 10% of the C method calls, with 87K calls, and the most called Ruby method is "only" called 26K times. It's also the topmost method in railsbench, where it's called about 4x more than the most frequently called Ruby methodsOn liquid-render it's at 6.3%. Note that in theory, in liquid-render, we already optimize Kernel#respond_to? and Array#[], so the overhead taken by Hash#[] is probably significant.
All of this is to say, Hash#[] gets called a lot on our benchmarks, more than basically any other C or Ruby method. Therefore, we should probably care about making sure that it runs fast. We probably don't want to generate JITted code for every single hash variable access because that might tie us a little too deeply with the specifics of the Ruby hash map implementation, which could get pretty messy, but there might still be some clever things we can do.
Right now, from what I can see, we do have some special handling for hash reads in opt_aref, which calls rb_hash_aref.
Some ideas:
- For hash keys that are symbols or string constants, could we precompute the hashed value somehow?
- For objects that we know are of the symbol or string class, could we avoid the
jit_prepare_routine_call? We should be able to know that there will be no call into Ruby methods and no GC alloc in some cases?- That would have the benefit of avoiding clearing local types as well
- I guess that might be somewhat tricky because we have to know
String#hashandSymbol#hashwasn't redefined?
- At the moment, as far as I can tell, we have a
Type::Hash, and we guard that the receiver is anrb_cHash, but we never upgrade the type in the context, so successive hash reads would always have to run the guards
Activity
k0kubun commentedon Jan 10, 2023
Some
Hash#[]stats taken from one interation of railsbench with adhoc tracing:empty?: 8.3%RHASH_AR_TABLE_P: 53.5%default.nil?: 90.6%size:Hash: 97.1%Rack::Utils::HeaderHash: 1.8%ActiveSupport::HashWithIndifferentAccess: 0.7%String:Symbol:String: 48.0%Symbol: 41.0%Integer: 3.7%Array: 1.2%Object: 1.0%ActiveSupport::Notifications::Fanout: 1.0%FalseClass: 0.9%NilClass: 0.9%Hash: 0.7%Thread: 0.6%Class: 0.5%TrueClass: 0.3%I thought of the same thing when I looked at the stats.
This idea seems promising. This should at least be possible forI take this back. See #482 (comment).opt_aref_with(but it's not used by railsbench, so it doesn't matter).k0kubun commentedon Jan 10, 2023
At least for
RHASH_AR_TABLE_Phashes, which usesrb_any_hash, it doesn't seem to respect#hashoverrides when a key isT_STRINGorT_SYMBOL(or some other builtin types).I failed to figure out what hash function
do_hashwould normally use from quick reading due to its function pointer call, which is used by non-RHASH_AR_TABLE_Phashes, but I guess the same thing would hopefully hold for consistency. (edit: I created a non-AR hash and tested that it doesn't call overridden #hash.)k0kubun commentedon Jan 11, 2023
Callers:
Top examples:
Rack::Request::Env#get_headerhttps://github.com/rack/rack/blob/925a4a6599ab26b4f3455b525393fe155d443655/lib/rack/request.rb#L63Concurrent::Collection::NonConcurrentMapBackend#[]https://github.com/ruby-concurrency/concurrent-ruby/blob/52c08fca13cc3811673ea2f6fdb244a0e42e0ebe/lib/concurrent-ruby/concurrent/collection/map/non_concurrent_map_backend.rb#L20Set#include?https://github.com/ruby/ruby/blob/00d58afb5d7f3cf3a553e1e8f75f31e4d8781fe7/lib/set.rb#L404ActiveRecord::InheritableOptions#initializehttps://github.com/rails/rails/blob/6e721d79ba9458317c93bb02590bbaa25c5a3649/activesupport/lib/active_support/ordered_options.rb#L77ActiveModel::LazyAttributeHash#[]https://github.com/rails/rails/blob/6e721d79ba9458317c93bb02590bbaa25c5a3649/activemodel/lib/active_model/attribute_set/builder.rb#L39Looking at those examples, it seems like you can't really assume a specific single key in majority of callsites unless you inline multiple frames (e.g. this should probably inline frames all the way up to
Hash#[]). Chain guards might be able to handle it better in railsbench, but it's likely not enough in actual applications.I find a couple of examples where precomputing a hash seems reasonable without inlining, but those were the only such examples that I've found so far:
Rails::Initializable::Initializer#beforehttps://github.com/rails/rails/blob/6e721d79ba9458317c93bb02590bbaa25c5a3649/railties/lib/rails/initializable.rb#L20Rails::Initializable::Initializer#afterhttps://github.com/rails/rails/blob/6e721d79ba9458317c93bb02590bbaa25c5a3649/railties/lib/rails/initializable.rb#L24We should still be able to do some optimization for String and Symbol, but for now, maybe not precomputing a hash of a key.
casperisfine commentedon Jan 11, 2023
The hashcode precomputing was the first thing I thought as well. Would it be possible to single out cases where a literal or constant is used? e.g.
env["HTTP_REFERER"].These are likely to be relatively common in some hotspots like Active Record attribute accessors, rack midlewares etc.
maximecb commentedon Jan 11, 2023
That's interesting and potentially promising. If we can rely on
Hash#[]not calling any Ruby method and not performing GC and not throwing an exception, then we could save a little bit of overhead and avoid dropping all currently known type information. Then we could also upgrade the type in the context and avoid repeated type checks in successive hash accesses.If the behavior is consistent, we could potentially add a test to Ruby spec to guarantee that behavior doesn't change too?
These methods that just index into a hash and return that are so silly and wasteful 🤦♀️ GAH... That being said we do try to pass type information into callees, so it's possible that these methods might get specialized for T_STRING or T_SYMBOL. We'd have to check how often that information is known in the context inside of
opt_aref.I would have thought so too, but at least according to Kokubun's data, this is unfortunately not the case at all. Though inlining might uncover some opportunities for that which we don't see right now.
casperisfine commentedon Jan 11, 2023
Keep in mind that railsbench contains very little applicative code. It's nice to bench Rails itself, but it's not 100% representative of an average Rails app.
maximecb commentedon Jan 11, 2023
That is true. We could compare stats from liquid to have a better idea how things might differ with a different use case that also uses hashes a lot.
k0kubun commentedon Jan 11, 2023
This might be a valid point. The example Jean raised in #482 (comment),
env["HTTP_REFERER"], is the only kind of code that usesopt_aref_with, which YJIT doesn't compile yet. Railsbench doesn't side-exit on that insn at all, but SFR does by 0.3%. It might be nice to support this for SFR, and this insn is where precomputing a key's hash is always possible.As to this specific code
env["HTTP_REFERER"], however, I think thisenvis often notHashbut a wrapper of it. It would go throughRack::Request::Env#get_header, which means that we don't use a literal when an actualHash#[]call happens. If all theopt_aref_withside exits are on non-Hash receivers, then it might be a waste of time to optimize it that way. We should probably add stats first.casperisfine commentedon Jan 11, 2023
Hum, right. It's kinda similar with Active Record attribute methods, we end up with generated code like:
So while the key is a literal, it doesn't directly access the Hash, so YJIT couldn't optimize this without first inlining.
casperisfine commentedon Jan 11, 2023
Erf, what I was trying to say is that the key is a constant literal, but the actual hash lookup happens two method calls lower.
maximecb commentedon Jan 11, 2023
We could certainly implement
opt_aref_with. Every little bit counts 👍k0kubun commentedon Jan 12, 2023
I started working on optimizing
opt_arefforHash#[]today. I failed to wrap it up today, but the idea is:rb_hash_arefcall intorb_hash_stlike_lookupandrb_hash_default_valuecalls.jit_prepare_routine_call:BOP_DEFAULTis not redefined for Hash (and the receiver is rb_cHash, which is already guarded)RHASH_PROC_DEFAULTflag (hencerb_hash_default_valuewon't call a Proc)rb_any_hashwon't call#hash)Hashproperty reads i.e.Hash#[]? #482 (comment)Type::Hashinjit_guard_known_classTHashandCHashand checkCHashinstead.jit_prepare_routine_call(and itsctx.clear_local_types) is skippedRHASH_PROC_DEFAULTis already guarded, skiprb_hash_default_valueand just extractRHASH_IFNONEin generated code.For the
:before/:aftercase, i.e. when a Symbol literal is used for theHash#[]call, maybe we could optimize therb_hash_stlike_lookuppart further by precomputing the hash. But I'll likely scope that out from the first PR.k0kubun commentedon Jan 12, 2023
It's not going as well as I hoped.
This is the change I thought of yesterday f718a9e (not including a
Hashtype upgrade, but I already tried it too). It's slightly slower than master, which might be due to the added guards. However, even just skippingjit_prepare_routine_calland upgradingHashtype, believing the property of compile-time values won't change without guards, doesn't make a significant impact either while it does seem to be skipped fairly often.We need a better idea than just skipping
jit_prepare_routine_calland upgrading type information toHash.k0kubun commentedon Jan 12, 2023
Since
Hash#fetchis still a regular method call, I also tried leveraging that code to implement a specialized cfunc codegen for it 0775c27, but it didn't give a significant speedup in activerecord and railsbench (whereHash#fetchis the third common C method) either.The cost of
rb_hash_stlike_lookupseems significant compared to the method call overhead or PC/SP save. Unfortunately the most commonHash#fetchcallsite also didn't have a literal; it looks up a value with an argument as a key. As of now, inlining a String/Symbol literal of a key all the way down to a Hash lookup callsite seems like the only impactful approach.I also started to feel that we should check not only call count stats but also time-based stats, using stackprof for example. If it also says that we spend a long time on Hash lookup callsites, well, it should continue to be a priority I guess.
maximecb commentedon Jan 13, 2023
It's too bad that these optimizations don't help. There's probably something to be done by reimplementing the underlying hash data structure, but that's probably not something we want to get into right away (might get pretty hairy?). If we did decide to do that, we'd probably want to profile the amount of time taken by each type of hash lookup. Might be interesting to gather such profiling data regardless, just as a data point.
Maybe even just a benchmark using benchmark/ips that compares time taken for:
maximecb commentedon Feb 1, 2023
Closing for now