Skip to content

Commit 9998161

Browse files
committed
Prevent modulo in places where we can check the length
NFC. We know maxLength must be positive and non-zero, and therefore, i += 1 will be the next index until we reach maxLength, in which case the result is 0. Rather than perform a modulo, which requires division, every time, we can just reset i when it reaches the end of the buffer.
1 parent 63a8d8c commit 9998161

File tree

1 file changed

+8
-2
lines changed

1 file changed

+8
-2
lines changed

stdlib/public/core/Sequence.swift

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -988,7 +988,10 @@ extension Sequence {
988988
ringBuffer.append(element)
989989
} else {
990990
ringBuffer[i] = element
991-
i = (i + 1) % maxLength
991+
i += 1
992+
if i >= maxLength {
993+
i = 0
994+
}
992995
}
993996
}
994997

@@ -1067,7 +1070,10 @@ extension Sequence {
10671070
} else {
10681071
result.append(ringBuffer[i])
10691072
ringBuffer[i] = element
1070-
i = (i + 1) % k
1073+
i += 1
1074+
if i >= k {
1075+
i = 0
1076+
}
10711077
}
10721078
}
10731079
return Array(result)

0 commit comments

Comments
 (0)