From d7412e4f331e2c9884839064d4f0a587b286f9c9 Mon Sep 17 00:00:00 2001 From: Hong Minhee Date: Sat, 27 Apr 2019 00:00:34 +0900 Subject: [PATCH] Optimize rerender loop by avoiding random access --- Libplanet/Blockchain/BlockChain.cs | 28 +++++++++++++++++++++------- Libplanet/Tx/Transaction.cs | 1 - 2 files changed, 21 insertions(+), 8 deletions(-) diff --git a/Libplanet/Blockchain/BlockChain.cs b/Libplanet/Blockchain/BlockChain.cs index 08dce11a563..3615f26082c 100644 --- a/Libplanet/Blockchain/BlockChain.cs +++ b/Libplanet/Blockchain/BlockChain.cs @@ -515,19 +515,30 @@ internal void Swap(BlockChain other) { // Finds the branch point. Block topmostCommon = null; - for (long i = Math.Min(other.Tip.Index, Tip.Index); i >= 0; i--) + long shorterHeight = + Math.Min(this.LongCount(), other.LongCount()) - 1; + for ( + Block t = this[shorterHeight], o = other[shorterHeight]; + t.PreviousHash is HashDigest tp && + o.PreviousHash is HashDigest op; + t = Blocks[tp], o = other.Blocks[op] + ) { - if (other[i].Equals(this[i])) + if (t.Equals(o)) { - topmostCommon = this[i]; + topmostCommon = t; break; } } // Unrender stale actions. - for (long i = Tip.Index; i > (topmostCommon?.Index ?? -1); i--) + for ( + Block b = Tip; + !(b is null) && b.Index > (topmostCommon?.Index ?? -1) && + b.PreviousHash is HashDigest ph; + b = Blocks[ph] + ) { - Block b = this[i]; var actions = b.EvaluateActionsPerTx(a => GetStates(new[] { a }, b.PreviousHash).GetValueOrDefault(a) ).Reverse(); @@ -554,9 +565,12 @@ internal void Swap(BlockChain other) } // Render actions that had been behind. - for (long i = topmostCommon.Index + 1; i <= Tip.Index; i++) + IEnumerable> blocksToRender = + topmostCommon is Block branchPoint + ? this.SkipWhile(b => b.Index <= branchPoint.Index) + : this; + foreach (Block b in blocksToRender) { - Block b = this[i]; var actions = b.EvaluateActionsPerTx(a => GetStates(new[] { a }, b.PreviousHash).GetValueOrDefault(a) ); diff --git a/Libplanet/Tx/Transaction.cs b/Libplanet/Tx/Transaction.cs index 8064de1f7f6..bf3ccc986b4 100644 --- a/Libplanet/Tx/Transaction.cs +++ b/Libplanet/Tx/Transaction.cs @@ -5,7 +5,6 @@ using System.Globalization; using System.IO; using System.Linq; -using System.Reflection; using System.Runtime.Serialization; using System.Security.Cryptography; using Libplanet.Action;