Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaFX Canvas delay

I'm trying to convert some Java2D code to JavaFX and I'm stuck with an issue regarding the performance of the JavaFX Canvas. At some point, I'll have to draw thousands of small circles on the screen.

My problem is that in the first drawing, my code takes a lot of time to execute. But if I have to perform a second drawing, it takes only a fraction of the time to draw (it is at least 10 times faster).

Is there anything I'm doing wrong? Is there any way to prevent that initial delay?

I wrote this code to test it. In this code I draw 500,000 circles at random positions on a 1000 x 1000 canvas (built previously). I linked this code to a button click event, and on the first time I click it takes 10 seconds to execute. But if I just click again, it takes only 0.025 seconds.

private void paintCanvas() {
    long initTime = System.currentTimeMillis();

    GraphicsContext cg = canvas.getGraphicsContext2D();
    cg.setFill(Color.WHITE);
    cg.fillRect(0, 0, canvas.getWidth(), canvas.getHeight());
    cg.setFill(Color.rgb(0, 0, 0, 0.1));

    Random rand = new Random();
    for (int i = 0; i < 500000; i++) {     
        cg.fillOval(1000 * rand.nextFloat(), 1000 * rand.nextFloat(), 2, 2);
    }

    long endTime = System.currentTimeMillis();
    System.out.println("Time spent on drawing:" + (endTime - initTime)/1000.0f);        
}

Actually there is no max number of new elements. It can vary from some hundreds to hundreds of thousands, depending of the users needs. And yes, it is ok if some elements pop in over time.

like image 933
Renato Rodrigues Avatar asked Nov 10 '22 08:11

Renato Rodrigues


1 Answers

Guys I thank you for all help. I sent the same question to the OpenJFX mailing list and one of the developers answered. It seems that my JavaFX 2.2 version still use a old model for growing the command buffer. The new version, JavaFX 8, uses a more efficient model which makes the first painting as fast as the subsequent ones.

Here is the answer I got:

Jim Graham (james.graham at oracle.com)

Mon May 12 21:17:19 UTC 2014

This is likely due to growing the command buffer which was done linearly at one point (probably still done that way in 2.2), but is now exponential in 8.0. The first render time is nearly instantaneous in 8.0, but takes a long time as you found when I try it with one of my old 2.x builds...

      ...jim
like image 154
Renato Rodrigues Avatar answered Nov 15 '22 07:11

Renato Rodrigues