Commit 8b42b7f
Optimize index bounds check for immutable sorted set and list (#53266)
* Optimize index bounds check for immutable sorted set and list
- The bounds check to determine if a given index is >= 0 and < this.Count
is only necessary on the first call to ItemRef.
- The recursive steps within ItemRef do not need to continuously
do this bounds check on these immutable data structures.
- Proof:
Elimination of index >= 0 bounds check:
The first call to ItemRef checks if index >= 0.
If we recurse on the left node, the index value does not change.
If we recurse on the right node, index > _left._count. Then
index - _left._count - 1 >= 0.
Elimination of index < this.Count:
The first call to ItemRef checks if index < this.Count. Then
the given index must lie somewhere in this tree and
(**) index < this.Count == left.Count + right.Count + 1.
If we recurse on the left node, the index value does not change
and a check is already made to determine that index < _left.Count.
If we recurse on the right node, then we need to be sure that
index - _left.count - 1 < _right.Count. But this is just a
rearrangement of (**).
* Remove redundant code
* Remove redundant assert
* Apply suggestions from code review
Change from internal to private for unchecked methods.
Co-authored-by: Stephen Toub <stoub@microsoft.com>
Co-authored-by: Stephen Toub <stoub@microsoft.com>1 parent 3319fa8 commit 8b42b7f
2 files changed
Lines changed: 15 additions & 4 deletions
File tree
- src/libraries/System.Collections.Immutable/src/System/Collections/Immutable
Lines changed: 7 additions & 2 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
195 | 195 | | |
196 | 196 | | |
197 | 197 | | |
| 198 | + | |
| 199 | + | |
| 200 | + | |
| 201 | + | |
| 202 | + | |
198 | 203 | | |
199 | 204 | | |
200 | 205 | | |
201 | | - | |
| 206 | + | |
202 | 207 | | |
203 | 208 | | |
204 | 209 | | |
205 | 210 | | |
206 | | - | |
| 211 | + | |
207 | 212 | | |
208 | 213 | | |
209 | 214 | | |
| |||
Lines changed: 8 additions & 2 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
260 | 260 | | |
261 | 261 | | |
262 | 262 | | |
| 263 | + | |
| 264 | + | |
| 265 | + | |
| 266 | + | |
| 267 | + | |
| 268 | + | |
263 | 269 | | |
264 | 270 | | |
265 | 271 | | |
266 | 272 | | |
267 | | - | |
| 273 | + | |
268 | 274 | | |
269 | 275 | | |
270 | 276 | | |
271 | 277 | | |
272 | | - | |
| 278 | + | |
273 | 279 | | |
274 | 280 | | |
275 | 281 | | |
| |||
0 commit comments