Recently Microsoft posted a blog post about .NET 6 performance improvements, which mentioned a lot of interesting things, one of which was Random.Shared.
This is a read-only static property, and a thread-safe object, this thing can help us simplify the use of Random objects.
Random.SharedProvides a thread-safe instance of Random that can be used from any thread at the same time。 Reference:The hyperlink login is visible.
First of all, we need to know that Random is not thread-safe, so if we want to use Random in multithreading, usuallyThread safety needs to be considered。 Since it is not thread-safe, we can create one when we use it, and new one every time, but in this case, the code is not concise enough, and on the other hand, it may create more random objects, and there is also a performance overhead.
Let's compare and test it with BenchmarkDotNet, and the code is as follows:
The Old method is that I always new a new Random object to generate a random number, and the New method calls the latest Random.Shared method provided in .NET 6. The test renderings are as follows:
We look at the mean average execution time with the new features10x boost。
(End)
|