Skip to content

Render Arbre trees into one shared buffer - #756

Open
senid231 wants to merge 7 commits into
activeadmin:masterfrom
senid231:perf/buffered-render
Open

senid231 wants to merge 7 commits into
activeadmin:masterfrom
senid231:perf/buffered-render

Conversation

@senid231

@senid231 senid231 commented Nov 23, 2026 •

Copy link
Copy Markdown

Rendering a large tree now allocates a fraction of the memory, and the output stays byte-identical. Before this change, every nesting level copied its subtree's HTML about five times (indent, ElementCollection#to_s, html_safe), and each text node built a throwaway Arbre::Context. Related to #67.

Elements write into one shared buffer, and the depth is passed down instead of walked up the parent chain. An object renders through the original methods when any rendering hook differs from Arbre's own. Each hook, and every super it calls, is compared with the original method, so this covers subclasses, a hook redefined in place, singleton methods, extend, and modules included or changed after the first render.

Results on a 500-row by 44-cell table:

Before After
Allocated (build and render) 2.08M objects, 223 MB 563k objects, 44 MB
Allocated by render 1.31M objects 15k objects
Build and render time 850 ms 420 ms
Peak RSS growth 88 MB 24 MB

An ActiveAdmin 4 index page with 500 rows allocates 1.08M objects instead of 2.36M, and its HTML is identical.

Verification: the compatibility examples in spec/arbre/unit/rendering_spec.rb also pass on 2.2.1. 50 edge cases match 2.2.1 byte for byte under ActiveSupport 8.1 and 7.1. ActiveAdmin v4.0.0.beta23's suite passes (1588 examples).

@senid231

Copy link
Copy Markdown
Author

@tagliala please take a look when you have time

@Fivell
Fivell requested a review from javierjulio November 23, 2026 16:43
@senid231

Copy link
Copy Markdown
Author

@javierjulio i see there are conflicts, once you do initial review i can rebase it on master

@javierjulio javierjulio left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@senid231 thank you. We'd welcome improvements to Arbre, our main concern is avoiding any breaking changes and keeping compatibility. I ran a review with Codex on Sol 6.2 which I've posted below.

The shared buffer cuts render allocations substantially. In a local 500-row, 44-cell table benchmark, render allocations fell from about 667,000 to 22,000 with identical HTML. The cases below still differ from the base revision.

  • Rendering overrides are skipped. Redefining Tag#opening_tag has no effect even on the first render because the method owner stays the same. After the first render, the cache also misses a to_s override prepended to an element’s singleton class or added to an already-included module. Render flags
  • Documents bypass the Tag#to_s chain. A wrapper prepended to Tag#to_s previously ran after the doctype. Document#to_s now skips it. A custom doctype returned as a plain string also changes the result’s html_safe? value from false to true. Document
  • Void tags can raise while rendering discarded text. input "☃".encode("UTF-16LE").html_safe previously rendered <input/>. The shared writer appends the text before discarding it, which raises Encoding::CompatibilityError. Tag writer
  • Attribute serialization changes. An override of tag.attributes.to_s no longer controls the rendered attributes. Also, if an attribute value’s to_s adds an attribute, the new writer raises because it is iterating over the live hash. The old serializer converted values after flattening the attributes. Tag writer · Attributes
  • Indentation hooks change behavior. A nested tag with parent? overridden to return false gains two spaces. The writer also reads indent_level before opening_tag, reversing the previous order. A custom indent_level of -1 now selects the last entry in SPACES where it previously raised ArgumentError. Child depth · Tag indentation
  • Text node behavior changes. A String subclass with a custom to_s renders the underlying string when nested in a tag. The old renderer used the override. Also, reading children on a frozen text node now raises FrozenError if the collection has yet to be initialized. Text node · String conversion
  • Default tag names become frozen. Span.new.tag_name.replace("em") previously changed that element’s tag name. It now raises FrozenError. Tag name cache
  • Tag#build changes its return value. Div.new.build("hello") returned {} and now returns nil. A custom build method that uses the result of super can break. Tag builder

Three changes would make these paths easier to maintain:

  • Share tag construction between build_tag and arbre_insert_tag. Both assign the parent, enter the builder context, and handle block arity and return values. Builder methods
  • Keep separator and escaping rules in one place. The new top-level and nested attribute writers repeat them. Attributes · Nested attributes
  • Keep builder dispatch decisions with the builder. The render cache now also decides when to bypass build, so future builder changes require edits to rendering code. Render flags

Please add regression specs for the compatibility cases above.

Each subtree's HTML used to be copied several times per nesting level,
and every text node built a throwaway Arbre::Context. Elements now write
into one buffer, and classes that override a rendering or building hook
keep going through that override, so output and API stay unchanged.

Co-Authored-By: Clanker
Builder methods hand their argument array straight to Tag#build's body
when build is still Arbre's own, and Element#build takes an anonymous
splat it never reads. Overridden or extended builds go the usual way.

Co-Authored-By: Clanker
Attributes are written in one pass, the opening and closing tags are
written inline, and the render-flag lookup reads two instance variables
instead of building an array. The override checks stay in place.

Co-Authored-By: Clanker
Overrides are now detected by comparing each method, and the supers it
calls, with Arbre's original, so redefining a hook in place or in a
module included later also falls back. The builder fast path is gone:
it changed Tag#build's return value and saved little time.

Co-Authored-By: Clanker
@senid231
senid231 force-pushed the perf/buffered-render branch from 0672777 to 7a65bdf Compare December 1, 2026 18:39
@senid231

senid231 commented Dec 1, 2026

Copy link
Copy Markdown
Author

Thanks for the review. I pushed 7a65bdf, which addresses each point, and rebased on master. The examples under "compatibility with the original renderer" in rendering_spec.rb pass on 2.2.1 and fail on the previous head.

  • Rendering overrides: each hook, and the supers it calls, is compared with Arbre's original method instead of checking its owner. A hook redefined on Tag itself now falls back. Modules included or prepended into an Arbre class, a singleton class or an extended object are watched, so methods added to them later reset the cache.
  • Document: Document#to_s is doctype + super again, so a Tag#to_s wrapper runs after the doctype and a plain-string doctype stays unsafe.
  • Void tags: the dropped children render into a scratch buffer, as indent did.
  • Attributes: an Attributes#to_s override on the class or on one instance is used. Values other than strings, symbols, numbers, booleans, nil and ClassList go through the original to_s, so a value's to_s can't change the hash while it is written.
  • Indentation: overriding parent? or parent counts as overriding indent_level. A tag with any of those renders through indent(opening_tag, content, closing_tag), so the call order and the ArgumentError for a negative level match 2.2.1.
  • Text nodes: only a plain String skips to_s. Freezing a text node builds its children and context first.
  • Tag names: tag_name returns an unfrozen copy again. The writer reads the cached class name directly, so rendering does not allocate it.
  • Tag#build: I removed the builder fast path. That restores the {} return value and removes arbre_insert_tag, the duplicate of build_tag. On the benchmark it saved about 140k allocations and no measurable time.
  • Attribute writer: top-level and nested pairs go through one writer.

The 500-row table now allocates 563k objects (2.08M on 2.2.1).

@senid231
senid231 requested a review from javierjulio December 1, 2026 18:43
@codecov

codecov Bot commented Dec 1, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.81931% with 7 lines in your changes missing coverage. Please review.
✅ Project coverage is 99.09%. Comparing base (03d7cd8) to head (7a65bdf).

Files with missing lines Patch % Lines
lib/arbre/element/rendering.rb 97.36% 4 Missing ⚠️
lib/arbre/html/attributes.rb 98.03% 1 Missing ⚠️
lib/arbre/html/document.rb 85.71% 1 Missing ⚠️
lib/arbre/html/tag.rb 98.41% 1 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##            master     #756      +/-   ##
===========================================
- Coverage   100.00%   99.09%   -0.91%     
===========================================
  Files           17       18       +1     
  Lines          459      774     +315     
===========================================
+ Hits           459      767     +308     
- Misses           0        7       +7     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@javierjulio

Copy link
Copy Markdown
Member

@senid231 before posting another review, I've opened #761 with additional integration tests to ensure Arbre rendering compatibility before and after this PR. Since you seem to have a deeper understanding of Arbre, it would help to get your review and thoughts there and to also run it against your branch and give any feedback. Thank you.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants