New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add new Performance/RedundantFetchBlock
cop
#126
Conversation
Good PR.
h = {a: 1}
h.fetch(:a) { NotDefinedYet } # => 1
NotDefinedYet = 42
h.fetch(:b) { NotDefinedYet } # => NotDefinedYet Autocorrecting the above will fail. That example is dubious, but some constants are autoloaded, etc. You could mark this cop as |
8d94862
to
927abc9
Compare
@marcandre Thanks for review!
|
Right, obviously you're right about Ranges & Complex, my bad.
|
So seems like the case when block returns a String isn't worth considering. Tested on |
Yes, that's the point, right, the block form will always best equal or slower when the key is missing. It's thus best to avoid the block form for strings. |
927abc9
to
e3900b9
Compare
@marcandre Yes, sure, you are correct! I mixed up Updated to check for strings. Thanks for patience! 😄 |
e3900b9
to
bf54541
Compare
bf54541
to
4ea100f
Compare
You were correct regarding Updated with usage of |
That's one of those cases that sit between style and performance. For me it's a given that you shouldn't be using a block unless you have to compute something, regardless of the performance implications. |
@bbatsov So, wdyt, is this better to be moved to |
I'm on the fence. @rubocop-hq/rubocop-core what do you think? |
Yeah, I think this cop can move to |
Transferred rubocop/rubocop#8147 |
Related reference - https://github.com/JuanitoFatas/fast-ruby#hashfetch-with-argument-vs-hashfetch--block-code
When block for
fetch
just returnsNumeric
,Symbol
,true
,false
,nil
or constant it is shorter (and faster) to pass an argument instead of using a block.When hash contains a key, performance is the same for argument vs block syntaxes, but when hash is missing a key - argument version is faster.
Benchmark
Results