Avoid copying back memory in FileChecksummer when data is valid #179
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
The current FileChecksummer almost always performs a memory copy once a read has occurred. This is because it fills the entire buffer, and every
Jump
call can, at most, consume half that buffer, leading tokeep
being greater than 0 in all cases except reaching the end-of-file.This seemingly unnecessary copying around of memory seems rather wasteful.
A solution may be to turn the buffer into some sort of circular buffer, however implementing such is rather complex/fiddly.
With the goal of simplicity, I've implemented a much easier approach that yields most of the benefit - instead of filling the buffer completely, only fill it half way, most of the time. Since the buffer can only be consumed til the half-way point, this is safe.
Assuming all data is valid, this makes
keep == 0
stay true throughout the process, avoiding the memory copy.This leaves cases where data isn't valid, causing
Step
orJump
(with smaller distances) to be called. In such cases, it just reverts to existing behavior of filling the buffer completely, and moving the data to the beginning of the buffer (inJump
s case). If the data becomes valid again, it'll revert to filling the buffer halfway.The assumption is that most data will be valid in typical usage scenarios, leading to a speedup most of the time.
Also the
memmove
inStep
can be replaced withmemcpy
as the regions are guaranteed to be non-overlapping.