any1 know how I can speed up Convert.ToByte? this is from float to byte..
I'm developing a 2D realtime image processing engine, and is too slow on the conversion from a floating point array, back to a System.Drawing.Bitmap. I am using FastBitmap to modify the bitmap, but it only happens when an image is taken in to the class and then thrown out again, converting from bitmap is ok, cause it only happens once or twice, but after that it's output is rendered in realtime animation. I'd like at least 50 Frame Per Second, which it only achieves at 320 by 240. And I have profiled it using ANTS. and apart from the obvious SafeNativeMethods.BitBlt (which is used by the picturebox to show the image) it shows Convert.ToByte as using the most time.
I am using floating point so I can do multipycation, and division (blending and effects) on each pixel, without doing any unnescesary conversions.
hope some1 has an idea ;)
Thanks, heaps.
DevinPosted May 16, 2008, 5:27 PM
AlanPosted May 16, 2008, 6:55 AM
If you look at the code for the Convert.ToByte(float) method using Reflector there are actually two more embedded calls:
public static byte ToByte(float value)
{
return ToByte((double) value);
}
public static byte ToByte(double value)
{
return ToByte(ToInt32(value));
}
public static byte ToByte(int value)
{
if ((value < 0) || (value > 0xff))
{
throw new OverflowException(Environment.GetResourceString("Overflow_Byte"));
}
return (byte) value;
}
So, it's no wonder that it's slow!
According to my rough tests, a simple cast:
byte b = (byte)value;
is about 4.5 times faster as it maps directly to the IL instruction, conv.u1.
Although it can cope OK with non-integral float values, there is no bounds checking in an unchecked context (the default) and so no exception is thrown for values outside the range 0 to 255. After conversion to an integer, only the lowest order byte is used and the rest are discarded.