-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
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
Fix key type for empty NamedTuple
be Symbol
#10942
Fix key type for empty NamedTuple
be Symbol
#10942
Conversation
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is technically breaking, but I'd consider it a bug fix. And it really shouldn't have a noteworthy negative impact.
Btw. is there any reason why |
No idea, @straight-shoota, I just made a minor change. I can change it to construct a literal? Edit: Done ✅ |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks @caspiano !
I was actually just asking about literal vs. construcing in general, not specifically asking to replace one by the other. 🙈 I'd like to explicitly consider which one's actually preferable. |
@straight-shoota I ran some benchmarks, looks like the literal approach is faster. require "benchmark"
struct NamedTuple
def literal_to_a
{% if T.size == 0 %}
[] of {Symbol, NoReturn}
{% else %}
[
{% for key in T %}
{ {{key.symbolize}}, self[{{key.symbolize}}] },
{% end %}
]
{% end %}
end
def dynamic_to_h
hash = Hash(typeof(first_key_internal), typeof(first_value_internal)).new(size)
each do |key, value|
hash[key] = value.as(typeof(first_value_internal))
end
hash
end
end
test = {
a: 1,
b: "1",
c: Time.unix(1),
d: [1]
}
puts "NamedTuple.to_a"
Benchmark.ips do |x|
x.report("literal") { test.literal_to_a }
x.report("each") { test.to_a }
end
puts "NamedTuple.to_h"
Benchmark.ips do |x|
x.report("literal") { test.to_h }
x.report("each") { test.dynamic_to_h }
end
|
|
Symbol
instead of NoReturn
as key type for empty NamedTuple
NamedTuple
be Symbol
This PR changes the semantics of
to_a
andto_h
on an emptyNamedTuple
and includes documentation of said behaviour.After this PR, the following behaviour is expected...
Resolves #9923
Resolves #10939