ChainSafe / ChainSafe/lodestar

Audit the use of Array.slice()

Open
#4,341 0 comments 1 reaction 0 assignees View on GitHub
prio-medium scope-memory
Dominant language
TypeScript
Stars
1.4k
Forks
483
Avg merge
1d 16h
Merged PRs (30d)
150

Description

**Is your feature request related to a problem? Please describe.**

Some `Array.slice()` is used unnecessarily just for api convenience, this not only affects performance (as a new array is copied) but also cause `gc` to run more frequently. Some examples:

1. archiveBlocks.ts:
```typescript
for (let i = 0; i < blocks.length; i += BATCH_SIZE) {
const toIdx = Math.min(i + BATCH_SIZE, blocks.length);
const canonicalBlocks = blocks.slice(i, toIdx);
```
then we loop `canonicalBlocks`. In this case we can just do a for loop over `i` and `toIdx`

2. stateContextCache

```typescript
prune(headStateRootHex: RootHex): void {
const keys = Array.from(this.cache.keys());
if (keys.length > this.maxStates) {
// object keys are stored in insertion order, delete keys starting from the front
for (const key of keys.slice(0, keys.length - this.maxStates)) {
```

in this case we can just do a regular `for` loop and break if it goes beyond the limit.

**Describe the solution you'd like**

Audit the use of `Array.slice()` in lodestar, only use it if it's really needed

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.