Skip to content

Conversation

swankjesse
Copy link
Collaborator

The old rangeEquals function was embarassingly inefficient, using a full scan of the segments linked-list for each element. That optimization is already done in indexOf(), which has almost all of what we need for rangeEquals().

This adds an offset and count slice to the input ByteString in indexOf(), and then leverages that to simplify rangeEquals().

The old rangeEquals function was embarassingly inefficient,
using a full scan of the segments linked-list for each element.
That optimization is already done in indexOf(), which has
almost all of what we need for rangeEquals().

This adds an offset and count slice to the input ByteString
in indexOf(), and then leverages that to simplify rangeEquals().
if (data[pos] == b0 && rangeEquals(s, pos + 1, targetByteArray, 1, bytesSize)) {
if (
data[pos] == b0 &&
rangeEquals(s, pos + 1, targetByteArray, bytesOffset + 1, byteCount)
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note that this rangeEquals() is fast, because it accepts a Segment for navigation.

return false
}
for (i in 0 until byteCount) {
if (this[offset + i] != bytes[bytesOffset + i]) {
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This was slow . . . walking through the segments linked list N times.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would this likely make the original buffering issue a non issue even before the okhttpo fixes landed?

Or just a performance win?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just a performance win.

@@ -418,19 +441,18 @@ internal inline fun RealBufferedSource.commonRangeEquals(
): Boolean {
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also reimplement BufferedSource.rangeEquals() on BufferedSource.indexOf(). Of course.

Copy link
Collaborator

@yschimke yschimke left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM - but don't put a lot of weight on me spotting something here.

@swankjesse swankjesse merged commit eca2120 into master May 27, 2025
11 checks passed
@swankjesse swankjesse deleted the jwilson.0526.faster_rangeEquals branch May 27, 2025 18:34
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants