Skip to content

Commit

Permalink
Reduce allocations in turbo_stream_action_tag (#415)
Browse files Browse the repository at this point in the history
This commit eliminates a few unnecessary allocations in
`turbo_stream_action_tag`:

**Benchmark**

  ```ruby
  # frozen_string_literal: true
  require "benchmark/memory"

  class Helpers
    include Turbo::Streams::ActionHelper
  end

  class Message
    include ActiveModel::API
    def to_key() = [1]
  end

  helpers = Helpers.new
  message = Message.new

  Benchmark.memory do |x|
    helpers.turbo_stream_action_tag("remove", target: message) # warmup

    x.report("turbo_stream_action_tag") do
      helpers.turbo_stream_action_tag("remove", target: message)
    end
  end
  ```

**Before**

  ```
  Calculating -------------------------------------
  turbo_stream_action_tag
                           2.554k memsize (     0.000  retained)
                          35.000  objects (     0.000  retained)
                          12.000  strings (     0.000  retained)
  ```

**After**

  ```
  Calculating -------------------------------------
  turbo_stream_action_tag
                           2.138k memsize (     0.000  retained)
                          31.000  objects (     0.000  retained)
                          12.000  strings (     0.000  retained)
  ```
  • Loading branch information
jonathanhefner committed Dec 31, 2022
1 parent 627a0cd commit a10ea27
Showing 1 changed file with 4 additions and 4 deletions.
8 changes: 4 additions & 4 deletions app/helpers/turbo/streams/action_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,18 +15,18 @@ def turbo_stream_action_tag(action, target: nil, targets: nil, template: nil, **
template = action.to_sym == :remove ? "" : tag.template(template.to_s.html_safe)

if target = convert_to_turbo_stream_dom_id(target)
tag.turbo_stream(template, **attributes.merge(action: action, target: target))
tag.turbo_stream(template, **attributes, action: action, target: target)
elsif targets = convert_to_turbo_stream_dom_id(targets, include_selector: true)
tag.turbo_stream(template, **attributes.merge(action: action, targets: targets))
tag.turbo_stream(template, **attributes, action: action, targets: targets)
else
tag.turbo_stream(template, **attributes.merge(action: action))
tag.turbo_stream(template, **attributes, action: action)
end
end

private
def convert_to_turbo_stream_dom_id(target, include_selector: false)
if target.respond_to?(:to_key)
[ ("#" if include_selector), ActionView::RecordIdentifier.dom_id(target) ].compact.join
"#{"#" if include_selector}#{ActionView::RecordIdentifier.dom_id(target)}"
else
target
end
Expand Down

0 comments on commit a10ea27

Please sign in to comment.