Why allocate space for this variable?

问题内容:

I found this and I wonder why there is a memory allocation on the the variable in the loop (…. 0x20;). It looks like the variable is simply filled up with spaces. But why would one do this when we initialize the byte variable with the size ?

long fileByteLength = package.Properties.Length;
byte[] fileContent = new byte[fileByteLength];
for (int i = 0; i < fileByteLength; i++)
{
    fileContent[i] = 0x20;
}
// Download the file aa a byteArray to the fileContent variable
package.DownloadToByteArray(fileContent, 0);

问题评论:

    
What is package? Please provide a Minimal, Complete, and Verifiable example.
    
it’s not really important what package is. The question is around memory allocation of a variable and why it would look like this.
– user3633222
1 hour ago
    
If it’s not important, then just delete the whole block of code and be happy.
    
This side effect of SOs moderators is kinda of a joke, simply because my rep is not there. You should ask yourself if you think that’s a proper comment, honestly!
– user3633222
1 hour ago
    
It works for me, if you think it’s a joke, feel free to go to meta and discuss some improvements.

答案:

答案1:

The obvious answer is: because the programmer wanted to have it filled up with spaces. Initializing it with the length means you get a lot of 0 bytes. Why did the programmer want spaces? I have no idea. The whole thing is bad cargo-cult programming (meaning somebody did it because he saw somebody else doing it, without understanding how it works or what it does).

You should either use a stream or use the return value of that method. If your quality guideline is “good programming”, then that loop has to be deleted and replaced by either of the above solutions.

My preference would be the stream (could be a MemoryStream) so that you get rid of all that byte-counting and buffer shifting and return-value-checking. That is what the stream abstraction was made for.

答案评论:

    
Thank you! Could it be a speed/optimization thing ?
– user3633222
1 hour ago
1  
I doubt that. It will be overwritten anyway. The only positive effect is that the array is filled with spaces in the end, even if less bytes are written. But again… just ignoring the return value and filling with spaces beforehand is the hackiest way to handle that. Like some 80’s C programmer read only half the API and decided to “optimize” it. It’s not optimized, it’s simply wrong.
    
Especially since this is only “working” (I would not consider it working, but you know what I mean) if the data is text. Everything else (images, files, whatever data) is seriously broken if you add spaces in the end.

原文地址:

https://stackoverflow.com/questions/47755155/why-allocate-space-for-this-variable

添加评论