Skip to content

Micro-optimization suggestion: Allocate less memory for Stopwatch object on the heap #111829

Description

@ymalich

The current implementation of the Stopwatch class has the field
private bool _isRunning.

In my opinion, this field is redundant and leads to the allocation of an additional 8 bytes of heap (in 64-bit mode).
Instead of accessing the _isRunning field, it is better to implement the property,

public bool IsRunning => _startTicks > 0;

The trick is that the implementation of the QueryPerformanceCounter() functions for Unix and Windows guarantees that at the moment of calling these functions, the value more then 0 will be saved in the _startTicks variable (otherwise it means the system counters do not work).
Therefore, it is safe to check _startTicks > 0 instead of _isRunning.
And in the Stop() function reset _startTicks = 0.

If no one has any objections, I could change the code and create a pull request to contribute.

I tested the changes in Windows on my side.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions