views:

570

answers:

4

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!

+1  A: 

I won't reference knuth but profile your code. Put some timestamps in and measure how long things are taking. Then you can spend your time in optimization well :)

Spence
+3  A: 

Have a look at Array.Copy it should be faster

Sam Saffron
+3  A: 

Since you are converting from byte to float you are not going to get any significant speedup. No Array.Copy or variation of memcopy can cope with that.

The only possible gain would be to 'poke' the byte value into a float. I don't know enough (about the implementation of float) to know if it will work and I honestly don't want to know either.

Henk Holterman
Yeah under MS.NET Framework, I don't think we should be poking bits underneath a float :)
Karl
+11  A: 

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.

Richard