Trick C# to NOT check your array's bounds for nothing! #shorts



Trick C# to NOT check your array's bounds for nothing! #shorts

Trick C# to NOT check your array's bounds for nothing! #shorts

Here is the game for you. A benchmark, populating an array before measuring the time to run through it.
And here is the benchmark for a common for loop. I am reading all elements into a variable, to make sure that the optimizer does not interfere by silently removing my test code.
The important part is that the indexer is checking the index against array’s bounds. That check costs.
Let me show you how you can move it out. A new test, with a peculiar name – local array. The difference is that I will take that array into a local variable. A shallow copy! But one that guarantees that nothing will change during the upcoming loop. The loop is the same as before, only working on the local array variable.
Enjoy the results! Consistently less time, because compiler did not have to check the index anymore. The array’s bounds cannot change this time. We are safe and fast.

Video courses:
Beginning Object-oriented Programming with C# ► https://codinghelmet.com/go/beginning-oop-with-csharp
Collections and Generics in C# ► https://codinghelmet.com/go/collections-and-generics-in-cs
Making Your C# Code More Object-oriented ► https://codinghelmet.com/go/making-your-cs-code-more-oo

Other courses at Pluralsight ► https://codinghelmet.com/go/pluralsight
Other courses at Udemy ► https://codinghelmet.com/go/udemy

Additional videos:
The Fastest Way to Modify a List in C# ► https://youtu.be/0oSN65eM-tc
Coding with GitHub Copilot – Beginner to Master ► https://youtu.be/B9DKv09IfT4
Want to Start with DDD? Try Ubiquitous Language First! ► https://youtu.be/_zWMjMUHinc
Using C# Record Types ► https://youtu.be/VouNkrgkH78
Covariance and Contravariance in C# ► https://youtu.be/Wp5iYQqHspg
How do Virtual Functions Work? ► https://youtu.be/b0IDTWoaUJ0

Practical Design playlist at YouTube ► https://youtube.com/playlist?list=PLSDYwLgFqaX78eEg_YKs0wHmOMi7_ggZr

Comments are closed.