Optimization ended up in casting an object at each method call

Posted by Aybe on Programmers See other posts from Programmers or by Aybe
Published on 2014-04-26T13:48:19Z Indexed on 2014/05/26 22:01 UTC
Read the original article Hit count: 351

I've been doing some optimization for the following piece of code :

public void DrawLine(int x1, int y1, int x2, int y2, int color)
{
    _bitmap.DrawLineBresenham(x1, y1, x2, y2, color);
}

After profiling it about 70% of the time spent was in getting a context for drawing and disposing it.

I ended up sketching the following overload :

public void DrawLine(int x1, int y1, int x2, int y2, int color, BitmapContext bitmapContext)
{
    _bitmap.DrawLineBresenham(x1, y1, x2, y2, color, bitmapContext);
}

Until here no problems, all the user has to do is to pass a context and performance is really great as a context is created/disposed one time only (previously it was a thousand times per second).

The next step was to make it generic in the sense it doesn't depend on a particular framework for rendering (besides .NET obvisouly).

So I wrote this method :

public void DrawLine(int x1, int y1, int x2, int y2, int color, IDisposable bitmapContext)
{
    _bitmap.DrawLineBresenham(x1, y1, x2, y2, color, (BitmapContext)bitmapContext);
}

Now every time a line is drawn the generic context is casted, this was unexpected for me.

Are there any approaches for fixing this design issue ?

Note :

© Programmers or respective owner

Related posts about c#

Related posts about design-patterns