optimize chain.size()

This commit is contained in:
Christopher Jeffrey 2016-01-05 16:07:11 -08:00
parent 8e698673a0
commit c6c75d509b
2 changed files with 27 additions and 8 deletions

View File

@ -44,6 +44,7 @@ function Chain(options) {
hashes: [],
// Get height by hash
heights: {},
count: 0,
lastTs: 0
};
@ -165,6 +166,7 @@ Chain.prototype._addIndex = function _addIndex(entry) {
this.index.entries[entry.height] = entry;
this.index.hashes[entry.height] = entry.hash;
this.index.heights[entry.hash] = entry.height;
this.index.count++;
this.tip = this.index.entries[this.index.entries.length - 1];
this.emit('tip', this.tip);
@ -207,6 +209,11 @@ Chain.prototype.resetHeight = function resetHeight(height) {
}, {});
this.index.hashes.length = height + 1;
if (!this.options.fullNode)
this.index.count -= this._count(ahead);
else
this.index.count = height + 1;
this.tip = this.index.entries[this.index.entries.length - 1];
this.emit('tip', this.tip);
@ -241,7 +248,7 @@ Chain.prototype.add = function add(block, peer) {
var initial = block;
var code = Chain.codes.unchanged;
var hash, prev, prevProbe, range, i, entry;
var hash, prev, i, entry;
for (;;) {
// Only validate the initial block (orphans were already validated)
@ -428,7 +435,7 @@ Chain.prototype.hashRange = function hashRange(start, end) {
hashes = this.index.hashes.slice(start.height, end.height + 1);
if (!this.options.fullNode)
hashes = hashes.filter(Boolean);
hashes = this._filter(hashes);
return hashes;
};
@ -516,10 +523,7 @@ Chain.prototype.getNextBlock = function getNextBlock(hash) {
};
Chain.prototype.size = function size() {
// This would get called alot. TODO: Optimize.
if (!this.options.fullNode)
return this.index.entries.filter(Boolean).length;
return this.index.entries.length;
return this.index.count;
};
Chain.prototype.height = function height() {
@ -594,13 +598,14 @@ Chain.prototype.compact = function compact(keep) {
this.index.entries = {};
this.index.hashes = [];
this.index.heights = {};
this.index.count = 0;
json.entries.forEach(function(entry) {
this._addIndex(ChainBlock.fromJSON(this, entry));
}, this);
};
Chain.prototype._compact = function _compact(keep) {
var entries = this.index.entries.filter(Boolean);
var entries = this._filter(this.index.entries);
if (!keep)
keep = 1000;
@ -666,6 +671,20 @@ Chain.prototype._delete = function(hash) {
});
};
Chain.prototype._count = function(obj) {
for (var i = 0, c = 0; i < obj.length; i++)
if (obj[i])
c++;
return c;
};
Chain.prototype._filter = function(obj) {
for (var i = 0, a = []; i < obj.length; i++)
if (obj[i])
a.push(obj[i]);
return a;
};
Chain.prototype.toJSON = function toJSON() {
var entries = this.index.entries;

View File

@ -529,7 +529,7 @@ Pool.prototype._addIndex = function _addIndex(block, peer) {
res = this.chain.add(block, peer);
if (res > 0)
if (res !== bcoin.chain.codes.okay)
this.emit('chain-error', bcoin.chain.msg(res));
// Do not emit if nothing was added to the chain