Skip to content

Commit

Permalink
Optimize rerender loop by avoiding random access
Browse files Browse the repository at this point in the history
  • Loading branch information
dahlia committed Apr 27, 2019
1 parent 48c27d5 commit d7412e4
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 8 deletions.
28 changes: 21 additions & 7 deletions Libplanet/Blockchain/BlockChain.cs
Expand Up @@ -515,19 +515,30 @@ internal void Swap(BlockChain<T> other)
{
// Finds the branch point.
Block<T> 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> t = this[shorterHeight], o = other[shorterHeight];
t.PreviousHash is HashDigest<SHA256> tp &&
o.PreviousHash is HashDigest<SHA256> 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<T> b = Tip;
!(b is null) && b.Index > (topmostCommon?.Index ?? -1) &&
b.PreviousHash is HashDigest<SHA256> ph;
b = Blocks[ph]
)
{
Block<T> b = this[i];
var actions = b.EvaluateActionsPerTx(a =>
GetStates(new[] { a }, b.PreviousHash).GetValueOrDefault(a)
).Reverse();
Expand All @@ -554,9 +565,12 @@ internal void Swap(BlockChain<T> other)
}

// Render actions that had been behind.
for (long i = topmostCommon.Index + 1; i <= Tip.Index; i++)
IEnumerable<Block<T>> blocksToRender =
topmostCommon is Block<T> branchPoint
? this.SkipWhile(b => b.Index <= branchPoint.Index)
: this;
foreach (Block<T> b in blocksToRender)
{
Block<T> b = this[i];
var actions = b.EvaluateActionsPerTx(a =>
GetStates(new[] { a }, b.PreviousHash).GetValueOrDefault(a)
);
Expand Down
1 change: 0 additions & 1 deletion Libplanet/Tx/Transaction.cs
Expand Up @@ -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;
Expand Down

0 comments on commit d7412e4

Please sign in to comment.