This article is a mirror article of machine translation, please click here to jump to the original article.

View: 23489|Reply: 5

[Source] [Actual combat]. NET 6 Random generates a random number test

[Copy link]
Posted on 2022-3-31 16:20:26 | | | |
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:
.NET/C# uses BenchmarkDotNet to test code performance
https://www.itsvse.com/thread-9576-1-1.html
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)






Previous:ASP.NET Core (twelve) front-end JS, CSS bundling, and compression
Next:ASP.NET Core (XIII) to determine whether it is an Ajax request or not
Posted on 2022-4-2 09:15:51 |
It's time to learn again
Posted on 2022-4-14 10:42:00 |
Come and learn, prostitute, thank you for sharing.
Posted on 2022-6-20 17:01:32 |
In the tank! Thanks for sharing
 Landlord| Posted on 2023-11-25 21:01:04 |
Use the GUID method to randomly select one from the collection (do not use it for database query, otherwise the full table will be queried)

 Landlord| Posted on 2025-4-6 09:33:00 |
Populate byte arrays with cryptographic random value sequences. (where System.Security.Cryptography.RNGCryptoServiceProvider is deprecated)


or
Disclaimer:
All software, programming materials or articles published by Code Farmer Network are only for learning and research purposes; The above content shall not be used for commercial or illegal purposes, otherwise, users shall bear all consequences. The information on this site comes from the Internet, and copyright disputes have nothing to do with this site. You must completely delete the above content from your computer within 24 hours of downloading. If you like the program, please support genuine software, purchase registration, and get better genuine services. If there is any infringement, please contact us by email.

Mail To:help@itsvse.com