Swing dashed line performance

Drawing dashed lines in Swing can be surprisingly slow, and worse, the default implementation seems to be sub-optimal.  Of course, for most apps, this isn’t a big deal, but performance-sensitive apps that draw a lot of dashed lines (or draw them often) can suffer.

The first thing to optimize is to only draw the portion of the line within the clipping region.  For example, if the clipping rectangle is (0,0)-(100,100), then drawing the line (0,0)-(1000,0) takes much more time than drawing (0,0)-(100,0).  It seems that Swing still processes each individual dash, even if they will never be drawn.  This is slightly tricky when the beginning of the line is outside the clipping region.  For example, consider a line with a dash length of 5 and a space length of 5.  Drawing (0,0)-(100,0) is not the same as (-25,0)-(100,0) because the phase of the dash is different.  (The first will start with a dash at X=0, but the second will start with a space.)  To clip the line properly, the distance between the original start point and the clipped start point must be an integer multiple of the period, which in this case is 10.  Therefore, the clipped line would be (-5,0)-(100,0).

To really squeeze out the last bit of performance, draw the dashed manually.  In other words, instead of using a dashed stroke and drawing (0,0)-(100,0), use a plain stroke and draw (0,0)-(5,0), (10,0)-(15,0), etc.  It seems like this should actually reduce performance, but it doesn’t.

I wrote a micro-benchmark to time these approaches.  I use a window that is 200 pixels wide, and draw a line from -1000 to 1200.  The results on my laptop are:

Approach Time (microseconds)
Naive 734.7
Clipped 126.4
Clipped & manual dashes 30.4
Non-dashed line 3.9

As you can see, the results are quite dramatic.

As with any optimization, results may vary.  I’m running this on a Linux laptop with a Java 1.7 HotSpot JVM.

Here’s the benchmark: DashedLineSpeedTest.java.  (I had to fiddle with the extension.  WordPress refuses to let me attach a .java file “for security reasons”, even though I’m an admin and I enabled the “Admins can upload any type of file” option.  Go figure.)

Post a Comment

Your email is never shared. Required fields are marked *

*
*