Skip to content

Value slots, preencoded control flow, and bytecode codegen - #149

Merged
fmcarvalho merged 13 commits into
developmentfrom
perf/value-slots
Oct 22, 2026
Merged

fmcarvalho merged 13 commits into
developmentfrom
perf/value-slots

Conversation

@BernardoPe

@BernardoPe BernardoPe commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

This PR adds value slots and preencoded control flow as a faster alternative to dynamic(), and adds bytecode generation for simple chains.

Value slots (textOf, rawOf, intOf, longOf, doubleOf, boolOf, attrOf, attrOfNullable) let a view read a single value from the model without creating a dynamic() block. The preprocessor stores each slot directly in the chain, so rendering does not need to resolve it as a dynamic block each time.

The same idea is used for forEachOf and whenOf. Their bodies are preencoded once as separate sub-chains, then reused during rendering. forEachIndexedOf works like forEachOf and also gives each item its position, starting at 0, so a view can number rows or alternate row classes without building a wrapper list.

For chains made up of static blocks and value slots, HtmlFlow can also generate a small class that writes directly to the output buffer. This removes the interpretation loop and avoids boxing for numeric slots. The generated bytecode is written directly, so this does not add a bytecode library dependency. If a chain cannot be compiled, it keeps using the interpreted version. Both paths produce the same output.

The changes also work with async views and hot reload.

template-benchmark when adapting the presentations and stocks views to use these features (tested locally):

image image

Here is what the views look like:

public class StocksHtmlFlowSlots {

    public static HtmlView<List<Stock>> view = HtmlFlow.view(StocksHtmlFlowSlots::templateStocks);

    private static void templateStocks(HtmlPage view) {
        view
            .html()
                .head()
                    // ... unchanged head: title, meta, link, script, style ...
                .__()
                .body()
                    .h1().raw("Stock Prices").__()
                    .table()
                        .thead()
                            .tr()
                                .th().raw("#").__()
                                .th().raw("symbol").__()
                                .th().raw("name").__()
                                .th().raw("price").__()
                                .th().raw("change").__()
                                .th().raw("ratio").__()
                            .__()
                        .__()
                        .tbody()
                        .forEachIndexedOf((List<Stock> stocks) -> stocks, (tbody, row) -> tbody
                            .tr()
                                .attrOf("class", row.read(r -> r.index() % 2 == 0 ? "odd" : "even"))
                                .td()
                                    .intOf(row.readInt(r -> r.index() + 1))
                                .__()
                                .td()
                                    .a()
                                        .attrOf("href", row.read(r -> "/stocks/" + r.item().getSymbol()))
                                        .rawOf(row.read(r -> r.item().getSymbol()))
                                    .__()
                                .__()
                                .td()
                                    .a()
                                        .attrOf("href", row.read(r -> r.item().getUrl()))
                                        .rawOf(row.read(r -> r.item().getName()))
                                    .__()
                                .__()
                                .td()
                                    .strong()
                                        .doubleOf(row.readDouble(r -> r.item().getPrice()))
                                    .__()
                                .__()
                                .td()
                                    .attrOfNullable("class", row.read(r -> r.item().getChange() < 0 ? "minus" : null))
                                    .doubleOf(row.readDouble(r -> r.item().getChange()))
                                .__()
                                .td()
                                    .attrOfNullable("class", row.read(r -> r.item().getRatio() < 0 ? "minus" : null))
                                    .doubleOf(row.readDouble(r -> r.item().getRatio()))
                                .__()
                            .__())
                        .__()
                    .__()
                .__()
            .__();
    }
}
public class PresentationsHtmlFlowSlots {

    public static HtmlView<Iterator<Presentation>> view =
        HtmlFlow.view(PresentationsHtmlFlowSlots::presentationsView);

    private static void presentationsView(HtmlPage view) {
        view.html()
            .head()
                // ... unchanged head: meta, title, link ...
            .__()
            .body()
                .div().attrClass("container")
                    .div().attrClass("page-header")
                        .h1().raw("JFall 2013 Presentations - htmlApi").__()
                    .__()
                    .forEachOf(PresentationsHtmlFlowSlots::all, div -> div
                        .div().attrClass("panel panel-default")
                            .div().attrClass("panel-heading")
                                .h3()
                                    .attrClass("panel-title")
                                    .rawOf(PresentationsHtmlFlowSlots::heading)
                                .__()
                            .__()
                            .div()
                                .attrClass("panel-body")
                                .rawOf(Presentation::getSummary)
                            .__()
                        .__()
                    )
                .__()
                .script().attrSrc("/webjars/jquery/3.1.1/jquery.min.js").__()
                .script().attrSrc("/webjars/bootstrap/3.3.7-1/js/bootstrap.min.js").__()
            .__()
        .__();
    }

    private static Iterable<Presentation> all(Iterator<Presentation> iter) {
        return () -> iter;
    }

    private static String heading(Presentation p) {
        return p.getTitle() + " - " + p.getSpeakerName();
    }
}

Depends on

This depends on xmlet/xsd2poet#2, which adds the slot methods, Slot<M> and forEachIndexedOf to the generated element API.

For now, this branch uses xsd2poet-java:1.0.11-SNAPSHOT, built locally.

@github-actions

Copy link
Copy Markdown
Contributor

Please run mvn spotless:apply locally to fix the formatting issues, then commit and push the changes.

@BernardoPe
BernardoPe force-pushed the perf/value-slots branch 2 times, most recently from e1846d3 to 44d37f0 Compare September 18, 2026 22:55
@github-actions

Copy link
Copy Markdown
Contributor

Please run mvn spotless:apply locally to fix the formatting issues, then commit and push the changes.

@github-actions

github-actions Bot commented Oct 9, 2026

Copy link
Copy Markdown
Contributor

Please run mvn spotless:apply locally to fix the formatting issues, then commit and push the changes.

@BernardoPe
BernardoPe force-pushed the perf/value-slots branch 2 times, most recently from af7a98c to 1ecd4dc Compare October 9, 2026 09:18
BernardoPe and others added 13 commits October 22, 2026 17:28
textOf, rawOf, intOf, longOf, doubleOf, boolOf, attrOf and
attrOfNullable read one value from the model without opening a
dynamic() block. The preprocessor records each slot as a node in the
chain it already builds, and the markup around the slot stays in the
static blocks on either side.

A dynamic block writes its own indentation on every render, so the
static block after it is trimmed. A slot writes none, so the
preprocessor keeps the whitespace after a slot.
Loops and conditionals whose bodies the preprocessor records once, each
into its own sub-chain, and replays at render time. Before, the only
way to loop or branch on the model was a dynamic() block, which runs
the template again on every render.

Recording a body saves and restores the whole recording state, so
loops and conditionals nest.
A chain made only of static blocks and value slots now compiles once
into a generated class, which drops the interpretation loop. Loop and
conditional bodies compile the same way.

The class has two methods with the same body. render appends to a
StringBuilder, where numeric slots go in without boxing. write takes
any other Appendable, which only accepts chars, so numbers go through
String.valueOf there. Neither one buffers.

The class file is written by hand, so there is no new dependency. The
generated methods never branch, so they need no StackMapTable. A chain
that holds any other node keeps using the linked chain.
The async chain hands off to the same sync nodes that value slots and
forEachOf use, so they need no async code of their own. These tests
check that: slots on both sides of an await, and a render that matches
the equivalent dynamic() block byte for byte.
HtmlViewVisitorHot threw UnsupportedOperationException for every slot,
forEachOf and whenOf. It has no preencoded chain, so a slot now reads
the current model and writes the value at once, through the same
format helper the chain uses. forEachOf and whenOf set the model for
the length of the body, the way visitDynamic already does for a block.
HtmlContinuation implements the new HtmlResolver interface, so a visitor
can hold either a continuation chain or a compiled chain behind one type.
execute(Object) becomes resolve(Object) in every continuation and caller,
including the Kotlin suspendable continuations.
ChainCompiler.compile returns an HtmlResolver: the generated class, or the
linked chain itself when the chain does not compile. Continuations no
longer hold a compiled field, and HtmlViewVisitor just copies whichever
resolver preprocessing returned, so there is no null check.

The generated class extends HtmlResolverCompiled and implements a single
write(Appendable, Object). The base class wraps the IOException, since the
generated method has no branches and cannot catch it. Like a continuation,
each visitor gets its own copy, a shallow clone that writes to the
visitor's output. Renderer and HtmlContinuationSyncCompiled are gone.

Async views no longer compile their chain, which HtmlViewVisitorAsync
never used.
With a single write(Appendable, Object) method, every number went through
String.valueOf, which allocated a String per number before appending it.
Numbers now go through small append helpers in HtmlContinuationSyncValue
that call StringBuilder.append(int|long|double) when the output is a
StringBuilder, and Integer/Long/Double.toString otherwise. The generated
code stays branchless.

On the stocks benchmark this brings the single method back to the speed
of the old StringBuilder-specific render method (234.2 vs 233.1 ops/ms),
and the allocation per 20-row render back to 6,192 B from 7,360 B.
Booleans and raw values get append helpers too, so the generated code
handles every slot except text and nullable attributes the same way.
The linked chain and the hot reload visitor now append through the same
helpers (appendValue replaces format), so numbers skip the String copy
there as well and each kind is formatted in one place.

Also: the reflective helper check runs once instead of per compiled
chain, the dead invokeVirtual opcode is gone, both HtmlFlow.view
overloads share one preencoded branch for MFE and plain views, and two
HtmlViewVisitor comments now describe the resolver.
Boolean.toString returns a constant and StringBuilder.append(Object) calls
String.valueOf anyway, so the instanceof check only pays off for numbers.
A hot async view preprocesses on every render and runs that chain
without copying it, so a compiled forEachOf or whenOf body still had
no visitor and threw a NullPointerException. recordBlock now returns
the body copied for the preprocessing visitor, as it did before the
HtmlResolver change.
@fmcarvalho
fmcarvalho merged commit 1bcba45 into development Oct 22, 2026
1 of 2 checks passed
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