From f25ead012738944e76e8357007a22a45d3ede3e2 Mon Sep 17 00:00:00 2001 From: Tomas Mikula Date: Thu, 21 Apr 2016 14:42:52 -0400 Subject: [PATCH] Less memory copying in FingerTree.mkTree. --- .../java/org/reactfx/util/FingerTree.java | 46 ++++++++++--------- 1 file changed, 24 insertions(+), 22 deletions(-) diff --git a/reactfx/src/main/java/org/reactfx/util/FingerTree.java b/reactfx/src/main/java/org/reactfx/util/FingerTree.java index a5d3cb5..952bdc0 100644 --- a/reactfx/src/main/java/org/reactfx/util/FingerTree.java +++ b/reactfx/src/main/java/org/reactfx/util/FingerTree.java @@ -822,37 +822,39 @@ public static FingerTree mkTree(List items) { } public static FingerTree mkTree( - List initialItems, + List items, ToSemigroup summaryProvider) { - if(initialItems.isEmpty()) { + + if(items.isEmpty()) { return new Empty<>(summaryProvider); } - List> leafs = new ArrayList<>(initialItems.size()); - for(T item: initialItems) { - leafs.add(new Leaf(summaryProvider, item)); + + ArrayList> trees = new ArrayList<>(items.size()); + for(T item: items) { + trees.add(new Leaf(summaryProvider, item)); } - return mkTree0(leafs); - } - private static FingerTree mkTree0(List> trees) { while(trees.size() > 1) { - for(int i = 0; i < trees.size(); ++i) { - if(trees.size() - i >= 5 || trees.size() - i == 3) { - NonEmptyFingerTree t1 = trees.get(i); - NonEmptyFingerTree t2 = trees.get(i + 1); - NonEmptyFingerTree t3 = trees.get(i + 2); - Branch branch = branch(t1, t2, t3); - trees.set(i, branch); - trees.subList(i + 1, i + 3).clear(); - } else { // (trees.size() - i) is 4 or 2 - NonEmptyFingerTree t1 = trees.get(i); - NonEmptyFingerTree t2 = trees.get(i + 1); - Branch b = branch(t1, t2); - trees.set(i, b); - trees.remove(i + 1); + final int n = trees.size(); + int src = 0; + int tgt = 0; + while(src < n) { + if(n - src >= 5 || n - src == 3) { + NonEmptyFingerTree t1 = trees.get(src++); + NonEmptyFingerTree t2 = trees.get(src++); + NonEmptyFingerTree t3 = trees.get(src++); + Branch t = branch(t1, t2, t3); + trees.set(tgt++, t); + } else { // (n - i) is 4 or 2 + NonEmptyFingerTree t1 = trees.get(src++); + NonEmptyFingerTree t2 = trees.get(src++); + Branch t = branch(t1, t2); + trees.set(tgt++, t); } } + trees.subList(tgt, n).clear(); } + return trees.get(0); }