A
aliostad
I have started programming with .NET 2.0 using Microsoft Visual Studio
2005
Version 8.0.50727.42 (RTM.050727-4200)
Microsoft .NET Framework
Version 2.0.50727
and I was doing some image processing and it was taking a long time to
process and finally I found that I used a switch and it made it slower:
private static bool GetBitonalValue(byte[] buffer, int x, int y,
int stride, PixelFormat pf, int threshold)
{
switch (pf)
{
case PixelFormat.Format1bppIndexed:
throw new InvalidOperationException("Image is
already bitonal.");
case PixelFormat.Format8bppIndexed:
byte b = buffer[(y * stride) + x];
return (b >= threshold);
case PixelFormat.Format24bppRgb:
byte[] bb = new byte[4];
bb[0] = 255;
Array.Copy(buffer, (y * stride) + x, bb, 1, 3);
Color clr = Color.FromArgb(BitConverter.ToInt32(bb,
0));
return ((clr.B + clr.G + clr.R) >= (threshold *
3));
case PixelFormat.Format32bppArgb:
case PixelFormat.Format32bppPArgb:
byte[] bbb = new byte[4];
Array.Copy(buffer, (y * stride) + x, bbb, 0, 4);
Color clr1 =
Color.FromArgb(BitConverter.ToInt32(bbb, 0));
return ((clr1.B + clr1.G + clr1.R) >= (threshold *
3));
default:
throw new NotImplementedException("Pixel format is
not supported.");
}
}
Regardless of the code itself, when I removed the switch it became 10
times faster. For an image of nearly 1000000 pixels it was taking 400ms
and after removing switch it took only 30ms for that part of code.
Is there anyway to optimise switch?
2005
Version 8.0.50727.42 (RTM.050727-4200)
Microsoft .NET Framework
Version 2.0.50727
and I was doing some image processing and it was taking a long time to
process and finally I found that I used a switch and it made it slower:
private static bool GetBitonalValue(byte[] buffer, int x, int y,
int stride, PixelFormat pf, int threshold)
{
switch (pf)
{
case PixelFormat.Format1bppIndexed:
throw new InvalidOperationException("Image is
already bitonal.");
case PixelFormat.Format8bppIndexed:
byte b = buffer[(y * stride) + x];
return (b >= threshold);
case PixelFormat.Format24bppRgb:
byte[] bb = new byte[4];
bb[0] = 255;
Array.Copy(buffer, (y * stride) + x, bb, 1, 3);
Color clr = Color.FromArgb(BitConverter.ToInt32(bb,
0));
return ((clr.B + clr.G + clr.R) >= (threshold *
3));
case PixelFormat.Format32bppArgb:
case PixelFormat.Format32bppPArgb:
byte[] bbb = new byte[4];
Array.Copy(buffer, (y * stride) + x, bbb, 0, 4);
Color clr1 =
Color.FromArgb(BitConverter.ToInt32(bbb, 0));
return ((clr1.B + clr1.G + clr1.R) >= (threshold *
3));
default:
throw new NotImplementedException("Pixel format is
not supported.");
}
}
Regardless of the code itself, when I removed the switch it became 10
times faster. For an image of nearly 1000000 pixels it was taking 400ms
and after removing switch it took only 30ms for that part of code.
Is there anyway to optimise switch?