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?
Share
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.