Skip to content

Commit a2017d6

Browse files
lechu445lechu445
andauthored
More optimized remainder calculation (#273)
Instead of division then remainder operation, used Math.DivRem which handles it in a more optimized way. It uses only a single division, multiplication, and subtraction instead of two divisions. Moreover, in the future, it can be even more optimized using intrinsics. See: dotnet/runtime#5213 (comment) Co-authored-by: lechu445 <[email protected]>
1 parent 55c265b commit a2017d6

File tree

1 file changed

+4
-5
lines changed

1 file changed

+4
-5
lines changed

src/RecyclableMemoryStream.cs

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1120,14 +1120,14 @@ public override void WriteByte(byte value)
11201120
{
11211121
var blockSize = this.memoryManager.BlockSize;
11221122

1123-
var block = (int)(this.position / blockSize);
1123+
var block = (int)Math.DivRem(this.position, blockSize, out var index);
11241124

11251125
if (block >= this.blocks.Count)
11261126
{
11271127
this.EnsureCapacity(end);
11281128
}
11291129

1130-
this.blocks[block][this.position % blockSize] = value;
1130+
this.blocks[block][index] = value;
11311131
}
11321132
else
11331133
{
@@ -1528,9 +1528,8 @@ public BlockAndOffset(int block, int offset)
15281528
private BlockAndOffset GetBlockAndRelativeOffset(long offset)
15291529
{
15301530
var blockSize = this.memoryManager.BlockSize;
1531-
int blockIndex = (int)(offset / blockSize);
1532-
int offsetIndex = (int)(offset % blockSize);
1533-
return new BlockAndOffset(blockIndex, offsetIndex);
1531+
int blockIndex = (int)Math.DivRem(offset, blockSize, out long offsetIndex);
1532+
return new BlockAndOffset(blockIndex, (int)offsetIndex);
15341533
}
15351534

15361535
private void EnsureCapacity(long newCapacity)

0 commit comments

Comments
 (0)