DrawRectangle vs DrawLine

Cags

Well-known member
Joined
Feb 19, 2004
Messages
690
Location
Melton Mowbray, England
Ive been working on an application that involved drawing a grid. In order to draw this grid I was originally using DrawRectangle to draw each individual square. Upon revisiting the code to optimise it I realised there are much faster ways to draw the grid as drawing each square indivually means that most lines between squares are drawn twice. To get around this I used the DrawLine function.

For example to draw a 9x9 grid, you only need to call DrawLine 20x as opposed to calling DrawRectangle 81x. Ok your all probably thinking well duh but bear with me. The same grid could be drawn by calling DrawLine 16x and 1x DrawRectangle (basically drawing the outline as a square instead of each individual line).

So what I was wondering is what are the overheads of each method? Does DrawRectangle encapsulate the same code as DrawLine? Which method actually takes longer to perform, DrawRectangle or DrawLine 4x. Obviously any difference is likely to be minimal and thus doesnt matter at all in the application Im working on. I was just intruiged if anyone would know.

Hope that makes sense.
 
in vb.net 2005 (for the stopwatch)

Code:
        Dim bm As New Bitmap(1000, 1000)
        Dim randomGenerator As New Random
        Dim rolex As New Stopwatch  implements IWish...
        Dim lots As Integer = 1000000 draw lines between pairs of points
        Dim points((lots / 2) - 1) As Point
        For i As Integer = 0 To points.Length - 1
            points(i) = New Point(randomGenerator.Next(0, 999), randomGenerator.Next(0, 999))
        Next
        Dim g As Graphics = Graphics.FromImage(bm)
        g.Clear(Color.White)
        rolex.Start()
        For i As Integer = 0 To (lots / 2) - 1 Step 2
            g.DrawLine(Pens.Black, points(i), points(i + 1))
        Next
        rolex.Stop()
        Debug.WriteLine("I drew " & ((lots / 2)).ToString & " lines in:" & rolex.ElapsedMilliseconds & "ms")

        we drew lots / 2 lines, so we want lots / 8 rectangles
        Dim recs((lots / 8) - 1) As Rectangle
        For i As Integer = 0 To (lots / 8) - 1
            recs(i) = New Rectangle(randomGenerator.Next(0, 999), randomGenerator.Next(0, 999), randomGenerator.Next(0, 999), randomGenerator.Next(0, 999))
        Next
        rolex.Reset()
        g.Clear(Color.White)
        rolex.Start()
        For i As Integer = 0 To ((lots / 8) - 1)
            g.DrawRectangle(Pens.Black, recs(i))
        Next
        rolex.Stop()
        Debug.WriteLine("I drew " & ((lots / 8)).ToString & " recs in:" & rolex.ElapsedMilliseconds & "ms")

I drew 500000 lines in:10397ms
I drew 125000 recs in:7187ms

so 1 rectangle is faster than 4 lines.
 
Back
Top