From c5dbadb66e63f1618e3f748c9540d956924a40e3 Mon Sep 17 00:00:00 2001 From: cha0s Date: Fri, 29 Apr 2022 04:35:48 -0500 Subject: [PATCH] perf: container sorting --- packages/graphics/src/container.js | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/packages/graphics/src/container.js b/packages/graphics/src/container.js index 6a3c343..ab51cfa 100644 --- a/packages/graphics/src/container.js +++ b/packages/graphics/src/container.js @@ -240,9 +240,22 @@ export default class Container extends Renderable { child.sort(); } } - this.$$children.sort((l, r) => l.$$zIndex - r.$$zIndex); - if (!this.container.isFake) { - this.container.children = this.$$children.map((child) => child.internal); + // Double insertion sort, because mostly-sorted is the usual case. + for (let i = 1; i < this.$$children.length; i++) { + const current = this.$$children[i]; + const currentChild = this.container.isFake ? undefined : this.container.children[i]; + let j = i - 1; + while ((j > -1) && (current.$$zIndex < this.$$children[j].$$zIndex)) { + this.$$children[j + 1] = this.$$children[j]; + if (!this.container.isFake) { + this.container.swapChildren(this.container.children[j], this.container.children[j + 1]); + } + j--; + } + this.$$children[j + 1] = current; + if (!this.container.isFake) { + this.container.swapChildren(currentChild, this.container.children[j + 1]); + } } }