Performing memory tasks efficiently
When benchmarking C# programs, you will see that sometimes, the objects that allocate the most memory will be faster than the methods that allocate fewer objects. A case in point is strings. Using formatted strings can allocate fewer memory interpolated strings. However, formatted strings can be slower than using interpolated strings. We are going to demonstrate this with a really simple piece of code:
- Add a class to the CH08_FileAndStreamIO project called
Memory
and configure it for using BenchmarkDotNet. - Add the
ReturnFormattedString()
method:[Benchmark] public string ReturnFormattedString() { return string.Format("{0} {1} {2} {3} {4} {5} {6} {7} {8} {9}", "The", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog", "." ); }
This method returns a formatted string...