Skip to content

Commit

Permalink
perf: use for-loop instead of forEach
Browse files Browse the repository at this point in the history
When looping use `for` loops instead, which _should_ be slightly faster.
Right?
  • Loading branch information
sebkolind committed May 29, 2024
1 parent 7ebca75 commit daacaa1
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 17 deletions.
18 changes: 12 additions & 6 deletions src/tags.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,11 @@ function createTag(context: Context) {
}

if (Array.isArray(children)) {
children.forEach((c) => {
for (let i = 0; i < children.length; i++) {
const c = children[i];

el.append(Array.isArray(c) ? createTag(c) : c);
});
}
} else {
el.append(typeof children === 'number' ? children.toString() : children);
}
Expand All @@ -32,7 +34,7 @@ function createTag(context: Context) {
}

const tags: Tags = {};
[
const tagsArray = [
'div',
'p',
'ul',
Expand Down Expand Up @@ -78,8 +80,12 @@ const tags: Tags = {};
'aside',
'small',
'b',
].forEach(
(tag) => (tags[tag] = (children, attrs) => createTag([tag, children, attrs])),
);
];

for (let i = 0; i < tagsArray.length; i++) {
const tag = tagsArray[i];

tags[tag] = (children, attrs) => createTag([tag, children, attrs]);
}

export { tags, createTag };
23 changes: 12 additions & 11 deletions src/walker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,34 +50,35 @@ function walker<A extends Attrs>(oldNode: TentNode<A>, newNode: TentNode<A>) {
}

if (oc.length < nc.length) {
nc.forEach((x, index) => {
if (oc[index] == null) {
oldNode.append(x);
for (let i = 0; i < nc.length; i++) {
if (oc[i] == null) {
oldNode.append(nc[i]);
}
});
}
}

if (oc.length > nc.length) {
oc.forEach((c, i) => {
for (let i = 0; i < oc.length; i++) {
if (nc[i] == null) {
c.remove();
oc[i].remove();
}
});
}
}

oc.forEach((oChild, index) => {
const nChild = nc[index];
for (let i = 0; i < oc.length; i++) {
const oChild = oc[i];
const nChild = nc[i];

if (nChild == null) {
return;
continue;
}

if (oChild.tagName !== nChild.tagName) {
oChild.replaceWith(nChild);
}

walker(oChild, nChild);
});
}
}

export { walker };

0 comments on commit daacaa1

Please sign in to comment.