Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Drastically reduce CPU usage and allocations #2

Merged
merged 1 commit into from
Feb 8, 2022

Conversation

canton7
Copy link

@canton7 canton7 commented Jun 18, 2021

SerialPort.Read takes a count parameter, which specifies the maximum
number of bytes to read from the serial port. If this is non-zero, then
the Read call will block until at least 1 byte has been received.

Previously, if there were no bytes available to read, then the code span
in a polling loop until a byte became available, burning CPU. It's more
efficient to call Read with a non-zero count parameter in this case,
which causes the thread to sleep until one or more bytes are available.

Change the Run method to follow the normal pattern of allocating a single
buffer, and then reading some number of bytes into it, and processing
just the bytes which were read. This also avoids the thousands of
allocations of single-byte arrays which were happening previously.

The _sleepTime field is now a bit redundent: I assume this was added
in an attempt to reduce CPU usage. I've left it in out of backwards
compatibility concerns, but it's not adding anything useful any more.

`SerialPort.Read` takes a `count` parameter, which specifies the maximum
number of bytes to read from the serial port. If this is non-zero, then
the `Read` call will block until at least 1 byte has been received.

Previously, if there were no bytes available to read, then the code span
in a polling loop until a byte became available, burning CPU. It's more
efficient to call `Read` with a non-zero `count` parameter in this case,
which causes the thread to sleep until one or more bytes are available.

Change the `Run` method to follow the normal pattern of allocating a single
buffer, and then reading some number of bytes into it, and processing
just the bytes which were read. This also avoids the thousands of
allocations of single-byte arrays which were happening previously.

The `_sleepTime` field is now a bit redundent: I assume this was added
in an attempt to reduce CPU usage. I've left it in out of backwards
compatibility concerns, but it's not adding anything useful any more.
@andywcoder
Copy link

Thanks for your contribution and sorry about my late response. Somehow I missed that pull request. Your change makes sense and I will accept the pull request. Please allow me some time until I publish an updated nuget package.

@andywcoder andywcoder merged commit 1152347 into BGLibExt:master Feb 8, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
2 participants