Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions crates/nsh-core/src/core/components.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1017,6 +1017,10 @@ pub(super) struct Components {
/// ([`Core::preceding`], `native_before_at`, `first_overlay_in`).
#[cfg(test)]
pub(super) placing_work: std::cell::Cell<usize>,
/// Children moved a place along by an insert before them
/// ([`Core::shifting`]).
#[cfg(test)]
pub(super) shift_work: std::cell::Cell<usize>,
/// Siblings looked at to find children's positions among them
/// ([`Core::positions_changed`], `position_bits`).
#[cfg(test)]
Expand Down Expand Up @@ -1260,6 +1264,8 @@ impl Default for Components {
#[cfg(test)]
placing_work: Default::default(),
#[cfg(test)]
shift_work: Default::default(),
#[cfg(test)]
position_work: Default::default(),
#[cfg(test)]
watch_work: Default::default(),
Expand Down Expand Up @@ -5198,6 +5204,18 @@ impl<M: TextEngine> Core<M> {
#[inline(always)]
pub(super) fn placing(&self, _n: usize) {}

/// `n` more children moved a place along by an insert before them
/// ([`Components::shift_work`]).
#[cfg(test)]
pub(super) fn shifting(&self, n: usize) {
let work = &self.components.shift_work;
work.set(work.get() + n);
}

#[cfg(not(test))]
#[inline(always)]
pub(super) fn shifting(&self, _n: usize) {}

/// `n` more mount items looked at for views taking the kind of their
/// component's root ([`Components::retag_work`]).
#[cfg(test)]
Expand Down
1 change: 1 addition & 0 deletions crates/nsh-core/src/core/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7875,6 +7875,7 @@ impl<M: TextEngine> Core<M> {
// Its logical parent changed: find its keyboard override again.
self.key_ancestry_dirty = true;
}
self.shifting(self.nodes[parent as usize].children.len() - pos);
self.nodes[parent as usize].children.insert(pos, child);
self.dirty_overlays();
self.raise_heights(child);
Expand Down
51 changes: 51 additions & 0 deletions crates/nsh-core/src/core/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27188,6 +27188,57 @@ mod views {
);
}

thread_local! {
static MANY: Cell<u32> = const { Cell::new(0) };
}

/// `MANY` rows of an `each`, then a view after them.
#[derive(Default)]
struct ManyRows;

impl Component for ManyRows {
type Props = RowsProps;
type Event = NoEvent;

fn view(_: RowsProps, _: Scope<NoEvent>) -> impl IntoElement {
let items = signal((0..MANY.with(Cell::get)).collect::<Vec<_>>());
view()
.child(text("before"))
.child(each(
items,
|n| *n,
|item, _| text(move || item.get().to_string()),
))
.child(text("after"))
}
}

/// An `each` mounted goes in before what follows it in order: placed
/// from the last, each row went before the one placed last and moved
/// every row placed so far, the square of the rows.
#[test]
fn an_each_mounts_its_rows_in_order_before_what_follows() {
let work = |rows: u32| {
MANY.with(|m| m.set(rows));
let mut c = core();
c.mount_root(&Root::new::<ManyRows>(|| RowsProps {}));
let batch = c.commit().unwrap();
let host = root_host(&batch);
let order = order(&c, host);
assert_eq!(order.len(), rows as usize + 2);
assert_eq!(order[1], "0");
assert_eq!(order[rows as usize], (rows - 1).to_string());
assert_eq!(order[rows as usize + 1], "after");
c.components.shift_work.get()
};
let (few, many) = (work(400), work(1_600));
// Four times the rows: about four times the work (sixteen before).
assert!(
many <= few * 6,
"{few} children moved for 400 rows, {many} for 1,600"
);
}

/// A list whose rows are regions: row 2 shows nothing until `LATE`.
#[derive(Default)]
struct RegionRows;
Expand Down
21 changes: 20 additions & 1 deletion crates/nsh-core/src/core/views.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
use std::{cell::RefCell, rc::Rc};

use super::{
Core,
Core, NO_KEY,
components::{Classes, Expanded, Instance, NewChild, Part, Placement},
};
use crate::{
Expand Down Expand Up @@ -827,6 +827,25 @@ impl<M: TextEngine> Core<M> {
{
return;
}
// All of them new (a region's first rows, an `each` mounted): each
// goes right before the anchor, in order. Placed from the last, each
// would go before the one placed last and move every node placed
// so far: n rows moved n²/2 children.
if !nested
&& nodes.iter().all(|&id| {
self.key(id)
.is_ok_and(|k| self.nodes[k as usize].parent == NO_KEY)
})
{
for &child in &nodes {
let _ = self.apply_op(Op::Insert {
parent,
child,
before,
});
}
return;
}
for &child in nodes.iter().rev() {
if nested {
if !self.nested_precedes(parent, child, before) {
Expand Down
44 changes: 40 additions & 4 deletions crates/nsh-js/src/dom.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1108,6 +1108,42 @@ unsafe extern "C" fn node_mark(rt: *mut qjs::JSRuntime, obj: JsValue, mark: qjs:

// --- The tree mirror ----------------------------------------------------------

/// Where `node` is among `children`, looked for from both ends at once: a
/// node rows are inserted before is most often near the end (what follows an
/// `<Each>`), one moved or removed near either end. Looked for from the
/// front alone, mounting n rows before what follows them looked at n²/2
/// children.
fn child_position(children: &[JsValue], node: JsValue) -> Option<usize> {
let (mut front, mut back) = (0, children.len());
while front < back {
looking(2);
if same(children[front], node) {
return Some(front);
}
back -= 1;
if same(children[back], node) {
return Some(back);
}
front += 1;
}
None
}

#[cfg(test)]
thread_local! {
/// Children [`child_position`] looked at, for tests of how that grows.
pub(crate) static CHILDREN_LOOKED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}

#[cfg(test)]
fn looking(n: usize) {
CHILDREN_LOOKED.with(|c| c.set(c.get() + n));
}

#[cfg(not(test))]
#[inline(always)]
fn looking(_: usize) {}

/// The node after `child` in its parent (`None`: the last one, or not a
/// child).
fn next_sibling(cx: *mut JsContext, child: JsValue) -> Option<JsValue> {
Expand All @@ -1122,7 +1158,7 @@ fn next_sibling(cx: *mut JsContext, child: JsValue) -> Option<JsValue> {
return None;
}
let children = unsafe { &(*p).children };
let i = children.iter().position(|&v| same(v, child))?;
let i = child_position(children, child)?;
children.get(i + 1).copied()
}

Expand Down Expand Up @@ -1218,14 +1254,14 @@ fn insert_before(
let op = d.by_id(old);
if !op.is_null() {
let children = unsafe { &mut (*op).children };
if let Some(i) = children.iter().position(|&v| same(v, child)) {
if let Some(i) = child_position(children, child) {
held = Some(children.remove(i));
}
}
}
let children = unsafe { &mut (*p).children };
let (pos, before_id) = match before {
Some(b) => match children.iter().position(|&v| same(v, b)) {
Some(b) => match child_position(children, b) {
Some(i) => (i, Some(unsafe { (*node_ptr(cx, b)).id })),
None => (children.len(), None),
},
Expand Down Expand Up @@ -1338,7 +1374,7 @@ fn remove_child(cx: *mut JsContext, parent: JsValue, child: JsValue) -> Result<(
return Ok(());
}
let children = unsafe { &mut (*p).children };
let Some(i) = children.iter().position(|&v| same(v, child)) else {
let Some(i) = child_position(children, child) else {
return Ok(());
};
let owned = children.remove(i);
Expand Down
26 changes: 26 additions & 0 deletions crates/nsh-js/src/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2000,6 +2000,32 @@ mod tests {
assert_eq!(Host::new().unwrap().target(), Release::FIRST_COMPATIBLE);
}

/// Nodes inserted before what follows them find it at once: looked for
/// from the front, n rows before a last child looked at n²/2 children.
#[test]
fn rows_inserted_before_a_last_child_look_at_few_children() {
let looked = |rows: usize| {
let host = Host::new().unwrap();
crate::dom::CHILDREN_LOOKED.with(|c| c.set(0));
host.eval_source(&format!(
r#"import {{ append, element, insert, text }} from "nsh:rt";
const view = element("view");
append(view, text("before"));
const after = text("after");
append(view, after);
insert(view, Array.from({{ length: {rows} }}, (_, i) => text(String(i))), after);"#
))
.unwrap();
crate::dom::CHILDREN_LOOKED.with(|c| c.get())
};
let (few, many) = (looked(400), looked(1_600));
// Four times the rows: about four times the looking (sixteen before).
assert!(
many <= few * 6,
"{few} children looked at for 400 rows, {many} for 1,600"
);
}

#[test]
fn strings_outside_a_text_are_reported_once_per_element() {
let host = Host::new().unwrap();
Expand Down
27 changes: 27 additions & 0 deletions docs/dev/performance.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,33 @@ Performance is the project's first priority; the rules are in `AGENTS.md`. Chang
after `nsh test --trace` timings and item counts (`nsh trace` before it, in the records below). Current baselines
(Apple Silicon except where noted):

An `each` mounted in time linear in its rows (`core/views.rs`, `nsh-js` `dom.rs`, 2026-12-04, macOS arm64, release,
against `7d33c400b`). Mounting n rows cost n² in two places:

- A Rust `each`'s region placed its new nodes from the last, each before the one placed last: every insert moved every
row placed so far. New nodes now go in order before the anchor.
- The renderer looked for the node it inserts before among the parent's children from the front. Rows go before what
follows them, near the end, so it now looks from both ends.

`cargo test --release -p nsh-core --lib bench_each_mount -- --ignored --nocapture` (`FakeEngine`, three alternating
runs), ms for the first mount:

| Rows of an `each` | 1,000 | 10,000 | 50,000 |
|---|---:|---:|---:|
| In a view | 4.1–13.8 → 4.7–14.5 | 52.5–55.0 → 47.1–58.6 | 506.9–511.4 → 249.2–306.5 |
| In a scroll view | 4.3–5.0 → 4.1–4.6 | 56.5–58.7 → 47.9–51.8 | 506.4–524.4 → 259.7–270.4 |

A TSX `<Each>` of texts between two texts in a scroll view, `nsh test --trace` (release, headless, three alternating
runs), ms for the first frame, with the JS evaluation in it:

| Rows | 20,000 | 80,000 |
|---|---:|---:|
| First frame | 131.8–135.3 → 69.2–74.9 | 1,340.5–1,347.9 → 334.1–341.5 |
| JS evaluation | 91.3–93.9 → 28.9–33.9 | 1,154.7–1,165.3 → 150.2–160.0 |

`examples/counter` and `examples/bench/RowsTs.tsx` keep their counts (56 ops and 50 mount items; 1,040 ops and 915 mount
items).

Layouts cached without the sides of the parent's size they do not read (`core/layout_tree.rs`, 2026-12-03, Linux
x86_64, AMD Ryzen 9 7950X, release, one CPU, against `de5c273e2`): Taffy keys a node's final layout by its parent's
size, so every row of a column whose height changed missed its cache and was laid out from scratch. A scroll view
Expand Down
Loading