From 480b67aaa0caa92c4a495ebb4ebf7e15dcb11c13 Mon Sep 17 00:00:00 2001 From: William Mantly Date: Tue, 15 Sep 2026 21:28:10 -0400 Subject: [PATCH] perf: batch DOM insertion through a DocumentFragment Adding several items at once did one .after() per item, so inserting into an attached, already-large container paid that container's cost once per item. Each item is still rendered individually -- it needs its own Mustache pass and its own __jq_$el -- but the DOM write is now a single fragment insert. Covers splice() with multiple additions (and therefore push(...items) and unshift(...items)), __sortedBatchAdd, and __syncDomOrder, so sort(), reverse() and sorted inserts benefit too. A single-item insert keeps the old path, where building a fragment would be pure overhead. Measured in Chrome on rows with realistic markup, one batched push: 1,000 rows 134ms -> 103ms, 2,000 rows 613ms -> 374ms, 4,000 rows 1,274ms -> 1,013ms. `put` still sees an element that is in the document at every call site; __sortedBatchAdd previously called it before insertion, alone among the call sites, and now matches the rest. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01TnJ9iEHU6m7kYxD5fXPfts --- CHANGELOG.md | 21 ++++++++ dist/js/jq-repeat.js | 94 +++++++++++++++++++++++++----------- dist/js/jq-repeat.min.js | 2 +- dist/js/jq-repeat.min.js.map | 2 +- package.json | 2 +- src/jq-repeat.js | 94 +++++++++++++++++++++++++----------- 6 files changed, 158 insertions(+), 57 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 824675e..00f38f7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,27 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +## [2.2.3] - 2026-09-16 + +### Changed +- **Batched DOM insertion.** Adding several items at once now renders each item + individually (each needs its own Mustache pass and its own `__jq_$el`) but + performs a single DOM write through a `DocumentFragment`, instead of one + `.after()` per item. Inserting one at a time pays the cost of touching an + attached, already-large container once per item; a fragment pays it once. + Applies to `splice()` with multiple additions, `push(...items)`, + `unshift(...items)`, `__sortedBatchAdd` and `__syncDomOrder` (so `sort()`, + `reverse()` and sorted inserts benefit too). A single-item insert keeps the + previous path, where a fragment would be pure overhead. + + Measured in Chrome on rows carrying realistic markup (nested spans, badges, + buttons), one batched push: 1,000 rows 134ms -> 103ms, 2,000 rows 613ms -> + 374ms, 4,000 rows 1,274ms -> 1,013ms. + + `put` is still called with the element already in the document, at every call + site. `__sortedBatchAdd` previously called it *before* insertion, alone among + the call sites; it now matches the rest. + ## [2.2.2] - 2026-08-30 ### Fixed diff --git a/dist/js/jq-repeat.js b/dist/js/jq-repeat.js index 36813d5..277197b 100644 --- a/dist/js/jq-repeat.js +++ b/dist/js/jq-repeat.js @@ -345,6 +345,54 @@ return $render; } + // Insert a batch of already-rendered elements after `anchor`, in order. + // + // One DOM write, not one per item. Inserting each element separately with + // .after() pays the cost of touching an attached, already-large container + // once per item; a fragment pays it once. Measured in Chrome on a table + // whose rows carry the markup a real app row does (nested spans, badges, + // buttons), comparing a single batched push before and after this change: + // 1,000 rows 134ms -> 103ms, 2,000 rows 613ms -> 374ms, 4,000 rows + // 1,274ms -> 1,013ms. Worth having, and it does not change the shape of + // the curve -- rendering stays ~0.3ms/row, so a caller that rebuilds a + // large list on every change still needs to rebuild less often. + // + // The elements are still rendered individually (each one needs its own + // Mustache pass and its own `__jq_$el`); only the DOM write is batched. + // `__put` is deliberately NOT called from here -- callers invoke it after + // this returns, so the hook still sees an element that is in the document. + __insertAfter(anchor, renderedList) { + if (!renderedList.length) return; + const $anchor = (anchor && anchor.length) ? anchor : this.$this; + + // A single element has nothing to batch, and building a fragment for it + // is pure overhead. + if (renderedList.length === 1) { + $anchor.after(renderedList[0]); + return; + } + + const anchorEl = $anchor[$anchor.length - 1]; + const parent = anchorEl && anchorEl.parentNode; + if (!parent) { + // Detached anchor (the placeholder before the list is in the + // document): nothing to optimise, and insertBefore would throw. + let previous = $anchor; + for (const $el of renderedList) { + previous.after($el); + previous = $el; + } + return; + } + + const frag = anchorEl.ownerDocument.createDocumentFragment(); + for (const $el of renderedList) { + const nodes = $el.get(); + for (let i = 0; i < nodes.length; i++) frag.appendChild(nodes[i]); + } + parent.insertBefore(frag, anchorEl.nextSibling); + } + __refreshIndexAttr(index, item) { if (!item || !item.__jq_$el) return; if (this.__jqIndexKey && item.hasOwnProperty(this.__jqIndexKey)) { @@ -428,18 +476,14 @@ previousElement = this.$this; } + const anchor = (previousElement && previousElement.length) ? previousElement : this.$this; + const rendered = []; for (let i = 0; i < toAdd.length; i++) { - let newItemData = toAdd[i]; - let $render = this.__renderItem(index + i, newItemData); - - if (previousElement && previousElement.length) { - previousElement.after($render); - } else { - this.$this.after($render); - } - previousElement = $render; - - this.__put($render, newItemData, this); + rendered.push(this.__renderItem(index + i, toAdd[i])); + } + this.__insertAfter(anchor, rendered); + for (let i = 0; i < toAdd.length; i++) { + this.__put(rendered[i], toAdd[i], this); } } @@ -481,7 +525,8 @@ } } - let previousElement = this.$this; + const ordered = []; + const freshlyRendered = []; for (let i = 0; i < this.length; i++) { const item = this[i]; if (!item) continue; @@ -490,17 +535,16 @@ if (!$el || !$el.length) { // New item: render fresh. $el = this.__renderItem(i, item); - this.__put($el, item, this); + freshlyRendered.push([$el, item]); } this.__refreshIndexAttr(i, item); - - if (previousElement && previousElement.length) { - previousElement.after($el); - } else { - this.$this.after($el); - } - previousElement = $el; + ordered.push($el); } + this.__insertAfter(this.$this, ordered); + // After insertion, so `put` sees an element that is in the document + // (it was previously called before the element was inserted here, + // unlike every other call site). + for (const [$el, item] of freshlyRendered) this.__put($el, item, this); } pop() { @@ -517,19 +561,15 @@ } } - let previousElement = this.$this; + const ordered = []; for (let i = 0; i < this.length; i++) { const item = this[i]; if (item && item.__jq_$el) { this.__refreshIndexAttr(i, item); - if (previousElement && previousElement.length) { - previousElement.after(item.__jq_$el); - } else { - this.$this.after(item.__jq_$el); - } - previousElement = item.__jq_$el; + ordered.push(item.__jq_$el); } } + this.__insertAfter(this.$this, ordered); return this; } diff --git a/dist/js/jq-repeat.min.js b/dist/js/jq-repeat.min.js index c681bb0..fb61ff8 100644 --- a/dist/js/jq-repeat.min.js +++ b/dist/js/jq-repeat.min.js @@ -1,3 +1,3 @@ /*! jq-repeat - MIT License - https://github.com/wmantly/jq-repeat */ -!function(){"use strict";class e{constructor(e){this.__callbacks=[];for(let t of Array.isArray(e)?e:[e])this.push(t)}push(e){e instanceof Function&&this.__callbacks.push(e)}call(){let e=arguments;this.__callbacks.forEach(t=>{t(...e)})}}!function(t,s){const r=new WeakMap;function n(e){const t=r.get(e);t&&(clearTimeout(t.timer),r.delete(e))}const i={};Object.defineProperty(i,"onNew",{value:new e,writable:!0,enumerable:!1,configurable:!0});let o=0;function a(e){if(!e||!e.__jqNested)return;const t=e.__jqNested;for(const e of Object.keys(t)){const s=t[e];s&&"function"==typeof s.empty&&s.empty(),s&&delete i[s.__jqRepeatId]}for(const e of Object.keys(t))delete t[e]}t.scope=new Proxy(i,{get:(e,t)=>"symbol"==typeof t?Reflect.get(e,t):"has"===t?t=>Object.prototype.hasOwnProperty.call(e,t):Object.prototype.hasOwnProperty.call(e,t)?Reflect.get(e,t):function(e,t){const s=[];let r=!1;const n=()=>{r||(r=!0,e[t]=s)};return new Proxy(s,{get(e,t,s){const r=Reflect.get(e,t,s);return"function"==typeof r?(n(),r.bind(e)):r},set:(e,t,s,r)=>(n(),Reflect.set(e,t,s,r))})}(e,t),set(e,t,s){return Reflect.set(...arguments)}});class h extends Array{static get[Symbol.species](){return Array}constructor(e,s,r,n,i,o,a,h,l){if(super(),this.__jqRepeatId=s,this.__jqBaseId=l||s,this.options=r,r&&void 0!==r.indexKey&&(this.__jqIndexKey=r.indexKey),r&&void 0!==r.orderBy){this.__jqOrderBy=r.orderBy;const e=r.orderReverse;this.__jqOrderReverse=null!=e&&!1!==e&&"false"!==e&&"0"!==e&&"no"!==e&&"off"!==e}else this.__jqOrderBy=null,this.__jqOrderReverse=!1;const _=r&&void 0!==r.updateDelay?Number(r.updateDelay):NaN;this.__jqUpdateDelay=Number.isFinite(_)&&_>=0?_:50,this._parentData=n,this.__jqParent=i,this.__jqParentIndex=o,this.__jqTemplate=a,this.nestedTemplates=h||[],Object.defineProperty(this,"__nestedTemplateCache",{value:this.nestedTemplates.map(e=>t(`${e}`)),writable:!0,enumerable:!1,configurable:!0}),this.$this=t(`