Live data from Hacker News

How we made a Ruby method 200x faster

campsite.com

1–10 of 48 posts

Re: How we made a Ruby method 200x faster

#2
That's a huge improvement but damn, the fixed code didn't look any better in my eyes.

Going from

  HANDLERS = [
    Text,
    List,
    ListItem,
    Code,
    # ...
  ].freeze
to

  HANDLERS_BY_NODE_NAMES = [
    Text,
    List,
    ListItem,
    Code,
    # ...
  ].each_with_object({}) do |handler, result|
    handler::NODE_NAMES.each { |node_name| result[node_name] = handler }
  end.freeze

Re: How we made a Ruby method 200x faster

#4

That's a huge improvement but damn, the fixed code didn't look any better in my eyes. Going from HANDLERS = [ Text, List, ListItem, Code, # ... ].freeze to HANDLERS_BY_NODE_NAMES = [ Text, List, ListItem, Code, # ... ].each_with_object({}) do |handler, result| handler::NODE_NAMES.each { |node_name| result[node_name] = handler } end.freeze

I'd go with this since it's not performance critical code. Not sure if it's that more readable, but I like it better:

    BY_NODE_NAMES = HANDLERS.map {|h|
      h::NODE_NAMES.map {|n| [n, h]}
    }.flatten(1).to_h

Re: How we made a Ruby method 200x faster

#5

That's a huge improvement but damn, the fixed code didn't look any better in my eyes. Going from HANDLERS = [ Text, List, ListItem, Code, # ... ].freeze to HANDLERS_BY_NODE_NAMES = [ Text, List, ListItem, Code, # ... ].each_with_object({}) do |handler, result| handler::NODE_NAMES.each { |node_name| result[node_name] = handler } end.freeze

A bigger question for me would be why the handlers don’t register themselves. It should be a very small amount of meta-programmation, and would avoid having to repeat the handlers to register them.

Re: How we made a Ruby method 200x faster

#6

That's a huge improvement but damn, the fixed code didn't look any better in my eyes. Going from HANDLERS = [ Text, List, ListItem, Code, # ... ].freeze to HANDLERS_BY_NODE_NAMES = [ Text, List, ListItem, Code, # ... ].each_with_object({}) do |handler, result| handler::NODE_NAMES.each { |node_name| result[node_name] = handler } end.freeze

[deleted]

Re: How we made a Ruby method 200x faster

#9
post #5

That's a huge improvement but damn, the fixed code didn't look any better in my eyes. Going from HANDLERS = [ Text, List, ListItem, Code, # ... ].freeze to HANDLERS_BY_NODE_NAMES = [ Text, List, ListItem, Code, # ... ].each_with_object({}) do |handler, result| handler::NODE_NAMES.each { |node_name| result[node_name] = handler } end.freeze

A bigger question for me would be why the handlers don’t register themselves. It should be a very small amount of meta-programmation, and would avoid having to repeat the handlers to register them.

Self-registration is usually an anti-pattern in my experience because it introduces globals. Sometimes you can't avoid it, but if you only have a few things to register it's usually better to just list them explicitly.
Post reply on HN