Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the fastest way to copy my array?

I'm doing some Wave file handling and have them read from disk into an array of bytes. I want to quickly copy portions from this byte array into another buffer for intermediate processing. Currently I use something like this:

float[] fin;
byte[] buf;
//fill buf code omitted
for(int i=offset; i < size; i++){
  fin[i-offset] = (float) buf[i];  
} 

I feel that this is a slow method, because there is as much computation going on in the for loop conditional and increment as there is over in the actual body. If there was a block copy avaliable in C# or some other way I can implement a block copy, that would be great.

Maybe it isn't too slow, but it sure looks like a lot of work to move some data over. Here "size" is between 2^10 and 2^14. I am then handing the "fin" off to a FFT library, so this is by no means the slowest part of the code, maybe I'm barking up the wrong tree.

EDIT UPDATE: I realize that micro optimizations are not where someone should spend their time, and I realize that profiling is a better way to achieve speedups overall, but I know that this code is in a 'hot path' and must be completed in under a third of a second on varying end user architectures to minimize our hardware system requirements. Even though I know that the following FFT code will be much more time consuming, I am looking for speedups where I can get them.

Array.Copy sure looks nice, I didn't know about that before, and I consider this Q&A a success already!

like image 884
Karl Avatar asked Dec 01 '22 08:12

Karl


1 Answers

There is also:

Array.Copy
Array.CopyTo

but whether these will be faster will require profiling.

But be warned about focusing on micro-optimisations to the extent you miss the big picture, on modern PCs the effect of multi-level memory caching is likely to be greater than one approach or another to the copy.

Edit: Quick check in reflector: both of the above methods boil down to a common native implementation (good).

Note the docs for Array.Copy cover valid type conversions, a value -> value widening conversion like byte to float should be OK.

like image 191
Richard Avatar answered Dec 04 '22 06:12

Richard