Add blockHeight cache in DaoState

Improve block lookup by height by introducing an index, instead of iterating through all blocks and comparing the height.
This commit is contained in:
cd2357 2021-05-11 12:03:46 +02:00
parent 792d135693
commit fea717eeab
No known key found for this signature in database
GPG Key ID: F26C56748514D0D3
2 changed files with 14 additions and 3 deletions

View File

@ -120,6 +120,7 @@ public class DaoStateService implements DaoSetupService {
daoState.getBlocks().clear();
daoState.getBlocks().addAll(snapshot.getBlocks());
daoState.setBlockHashCache(snapshot.getBlockHashCache());
daoState.setBlockHeightCache(snapshot.getBlockHeightCache());
daoState.getCycles().clear();
daoState.getCycles().addAll(snapshot.getCycles());
@ -311,9 +312,7 @@ public class DaoStateService implements DaoSetupService {
}
public Optional<Block> getBlockAtHeight(int height) {
return getBlocks().stream()
.filter(block -> block.getHeight() == height)
.findAny();
return Optional.ofNullable(daoState.getBlockHeightCache().get(height));
}
public boolean containsBlock(Block block) {

View File

@ -109,6 +109,8 @@ public class DaoState implements PersistablePayload {
@JsonExclude
private transient final Map<String, Tx> txCache; // key is txId
@JsonExclude
private transient final Map<Integer, Block> blockHeightCache; // key is block height
@JsonExclude
private transient final Set<String> blockHashCache;
///////////////////////////////////////////////////////////////////////////////////////////
@ -165,6 +167,9 @@ public class DaoState implements PersistablePayload {
blockHashCache = blocks.stream()
.map(Block::getHash)
.collect(Collectors.toSet());
blockHeightCache = blocks.stream()
.collect(Collectors.toMap(Block::getHeight, Function.identity(), (x, y) -> x, HashMap::new));
}
@Override
@ -260,6 +265,11 @@ public class DaoState implements PersistablePayload {
this.blockHashCache.addAll(blockHashCache);
}
public void setBlockHeightCache(Map<Integer, Block> blockHeightCache) {
this.blockHeightCache.clear();
this.blockHeightCache.putAll(blockHeightCache);
}
public Map<String, Tx> getTxCache() {
return Collections.unmodifiableMap(txCache);
}
@ -268,6 +278,8 @@ public class DaoState implements PersistablePayload {
return Collections.unmodifiableSet(blockHashCache);
}
public Map<Integer, Block> getBlockHeightCache() { return Collections.unmodifiableMap(blockHeightCache); }
@Override
public String toString() {
return "DaoState{" +