Reputation: 6762
I am writing a function that uses several byte arrays. However, I only need to keep the most recent one at any given time. Is there anything wrong with declaring a single byte[] at the start of my function (before the main loop) and then just keep assigning the most recent value to it? Conversely, is making a byte array instance and variable at each stage of my function a better practice? Would this repetitive allocation result in a performance loss?
Upvotes: 3
Views: 1867
Reputation: 4727
When you declare an array, unlike in C/C++, the array is allocated on the heap, and you're variable is actually a reference to the array. Therefore reusing the same variable will not save you from reallocating memory. If the arrays were exactly the same size then you could allocate it once and reuse the same object, the there would be a significant performance gain. The only gain you might have of reusing the same reference is that once you point it to a new array the old one is free to be garbage collected, although there are other ways to achieve this, like setting it to null.
Upvotes: 4
Reputation: 27353
There's no difference in the amount of work required to do either of those. The compiler will transform them to an identical implementation.
The most important thing to note is that in C#, unless you say "new", a variable declaration won't actually commit any resources. If you're fluent in C++, you should imagine that all C# variable declarations have an implicit * associated with them. For example in your case: byte[] *onePageOfBytes
. The function that you're asking to give you the byte array will do the actual allocation, and unless it knows how to recycle previous arrays, you don't have anything to gain by trying to avoid variable definitions.
Upvotes: 2