Skip to content

Commit eeeb833

Browse files
committed
A way to cache index offset.
1 parent ba41ee1 commit eeeb833

File tree

1 file changed

+29
-6
lines changed

1 file changed

+29
-6
lines changed

src/virtual.js

Lines changed: 29 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ export default class Virtual {
2929
// benchmark data
3030
this.__bsearchCalls = 0
3131
this.__getIndexOffsetCalls = 0
32+
this.__getIndexOffsetCacheHits = 0
3233
}
3334

3435
destroy () {
@@ -118,16 +119,38 @@ export default class Virtual {
118119
return low > 0 ? --low : 0
119120
}
120121

121-
getIndexOffset (index) {
122-
// remember last calculate index.
123-
this.lastCalculatedIndex = Math.max(this.lastCalculatedIndex, index - 1)
124-
this.lastCalculatedIndex = Math.min(this.lastCalculatedIndex, this.getLastIndex())
122+
// return a scroll offset from given index.
123+
getIndexOffset (givenIndex) {
124+
// we know this!
125+
if (!givenIndex) {
126+
this.__getIndexOffsetCacheHits++
127+
return 0
128+
}
129+
130+
// get from cache avoid too much calculate.
131+
if (givenIndex in this.offsetCaches) {
132+
this.__getIndexOffsetCacheHits++
133+
return this.offsetCaches[givenIndex]
134+
}
125135

126136
let offset = 0
127-
while (index--) {
137+
let indexOffset = 0
138+
for (let index = 0; index <= givenIndex; index++) {
128139
this.__getIndexOffsetCalls++
129-
offset = offset + (this.sizes[this.param.uniqueIds[index]] || this.getEstimateSize())
140+
141+
// cache last index index offset if exist.
142+
if (index && indexOffset) {
143+
this.offsetCaches[index] = offset
144+
}
145+
146+
indexOffset = this.sizes[this.param.uniqueIds[index]]
147+
offset = offset + (indexOffset || this.getEstimateSize())
130148
}
149+
150+
// remember last calculate index.
151+
this.lastCalculatedIndex = Math.max(this.lastCalculatedIndex, givenIndex - 1)
152+
this.lastCalculatedIndex = Math.min(this.lastCalculatedIndex, this.getLastIndex())
153+
131154
return offset
132155
}
133156

0 commit comments

Comments
 (0)