Michael Heinrichs

About Michael Heinrichs

Java, Android, JavaFX developer. Interested in agile management and public speaking. Loves his family and cooking.

Best Practices for JavaFX Mobile Applications, Part 1

As everybody who is interested in JavaFX will know by now, JavaFX Mobile was released a short while
ago. It was a hell of a ride, that’s for sure. I felt so exhausted, I did not even have the energy to blog during the release…

But by now I feel recovered and want to start a little series about lessons we have learned while preparing the release and give some hints how to improve the performance of JavaFX Mobile applications.

WARNING: The tips I am giving here are true for the current version of JavaFX Mobile, which is part of the JavaFX 1.1 SDK. In future versions the behavior will change, the
current bad performance of the mentioned artifacts will be optimized away or at least significantly improved. Everything I am writing about here is a snap-shot, nothing should be understood as
final!

Item 1: Avoid unnecessary bindings
Bindings are very convenient, without any doubt one of the most valuable innovations in JavaFX Script. Unfortunately they come with a price. The generated boiler-plate code is usually not as small and
fast as a manual implementation would be. Especially complex dependency-structures tend to impose a severe penalty on performance and footprint.

For this reason it is recommended to avoid bindings as much as possible. Often the same functionality can be implemented with triggers. One should not use bindings to avoid the hassle of dealing with the initialization order. And it certainly makes no sense to bind to a constant value.
Lazy bindings are most of the time (but not always!) faster if a bound variable is updated more often then read, but they are still not as fast as manual implementations.

Example
A common use-case is a number of nodes which positions and sizes depend on the stage-size. A typical implementation uses bindings to achieve that.
Here we will look at a simple example, which resembles such a situation. The scene consists of three rectangles which are laid out diagonally from the top-left to the bottom-right. The size of the rectangle is a quarter of the screen-size. Code Sample 1 shows an implementation with bindings.

def rectangleWidth: Number = bind stage.width * 0.25;
 def rectangleHeight: Number = bind stage.height * 0.25;

 def stage: Stage = Stage {
     scene: Scene {
         content: for (i in [0..2])
             Rectangle {
                 x: bind stage.width * (0.125 + 0.25*i)
                 y: bind stage.height * (0.125 + 0.25*i)
                 width: bind rectangleWidth
                 height: bind rectangleHeight
             }
     }
 }

Code Sample 1: Layout calculated with bindings
The first question one should think about is wether the bindings are really necessary. On a real device the screen-size changes only when the screen orientation is switched (provided that the device supports this functionality). If our application does not support screen rotation, the layout can be defined constant.
One possible solution to reduce the number of bindings is shown in Code Sample 2. Two variables width and height are introduced and bound to stage.width and stage.height respectively. Their only purpose is to provide triggers for stage.width and stage.height, since we do not want to override the original triggers. Position and size of the rectangles are calculated manually in the triggers.

def r = for (i in [0..2]) Rectangle {}

 def stage = Stage {
     scene: Scene {content: r}
 }

 def height = bind stage.height on replace {
     def rectangleHeight = height * 0.25;
     for (i in [0..2]) {
         r[i].height = rectangleHeight;
         r[i].y = height * (0.125 + 0.25*i)
     }
 }

 def width = bind stage.width on replace {
     def rectangleWidth = width * 0.25;
     for (i in [0..2]) {
         r[i].width = rectangleWidth;
         r[i].x = width * (0.125 + 0.25*i)
     }
 }

Code Sample 2: Layout calculated in trigger
Without any doubt, the code in Code Sample 1 is more elegant. But measuring the performance of both snippets in the emulator, it turned out the code in Code Sample 2 is almost twice as fast.

Further below we are going to see about the second tip to increase performance of JavaFX Mobile applications. I think this and the previous one are the most important ones.

WARNING: The tips I am giving here are true for the current version of JavaFX Mobile, which is part of the JavaFX 1.1 SDK. In future versions the behavior will change, the
current bad performance of the mentioned artifacts will be optimized away or at least significantly improved. Everything I am writing about here is a snap-shot, nothing should be understood as
final!

Item 2: Keep the scenegraph as small as possible
Behind the scenes of the runtime a lot of communication takes place to update the variables of the nodes in a scenegraph. The more elements a scenegraph has, the more communication is required. Therefore it is critical to keep the scenegraph as small as possible. Especially animations tend to suffer from a large scenegraph.
It is bad practice to keep a node in the scenegraph at all times and control its visibility via the visible-flag or its opacity. Invisible nodes in the scenegraph are still part of the communication-circus in the background. Instead one should remove nodes from the scenegraph and add them only when required.
This approach has one drawback though. Adding or removing nodes takes longer than setting the visibility. Therefore it might not be appropriate in situations were immediate responses are critical.

Example 1
Often one has a set of nodes of which only one is visible. These can be for example different pages, or nodes to visualize different states of an element. One might be tempted to add all nodes to the scenegraph and set only the current as visible.

Code Sample 1 shows a simplified version of this approach. Three colored circles are created to visualize some kind of state (red, yellow, green). Only one node is visible at any time. (Let’s ignore for a second that this could simply be achieved by changing the fill-color of a single circle. In real life applications one would probably have images or more complex shapes for visualizations and simply changing the color would not work.)

def colors = [Color.GREEN, Color.YELLOW, Color.RED];

 var state: Integer;

 Stage {
     scene: Scene {
         content: for (i in [0..2])
             Circle {
                 centerX: 10
                 centerY: 10
                 radius: 10
                 fill: colors[i]
                 visible: bind state == i
             }
     }
 }

Code Sample 1: Using visibility to switch between nodes
This results in three nodes in the scenegraph although only one is shown. This should be refactored to ensure that only the visible node is in the scenegraph. Code Sample 2 shows one possible implementation.

def colors = [Color.GREEN, Color.YELLOW, Color.RED];

 var state: Integer on replace oldValue {
     insert nodes[state] into stage.scene.content;
     delete nodes[oldValue] from stage.scene.content;
 }


 def nodes = for (i in [0..2])
     Circle {
         centerX: 10
         centerY: 10
         radius: 10
         fill: colors[i]
     }

 def stage = Stage {scene: Scene{}}

Code Sample 2: Adding and removing nodes when required
The code in Code Sample 1 is more compact, but Code Sample 2 reduced the number of nodes in the scenegraph from three to one. While tuning some of the demos for the JavaFX Mobile release, we were able to reduce the number of nodes in the scenegraph by 50% and more, simply by ensuring that only visible nodes are part of it.

Example 2
If nodes are shown and hidden with some kind of animation, adding and removing the node to the scenegraph becomes extremely simple. One only needs to implement an action at the beginning of the fadeIn-animation and at the end of the fadeOut-animation to add respectively remove the node. Code Sample 3 shows such a usage where a simple message-box is shown and hidden by changing the opacity.

def msgBox = Group {
     opacity: 0.0
     content: [
         Rectangle {width: 150, height: 40, fill: Color.GREY},
         Text {x: 20, y: 20, content: "Hello World!"}
     ]
 }

 def fadeIn = Timeline {
     keyFrames: [
         KeyFrame {
             action: function() {insert msgBox into stage.scene.content}
         },
         at (1s) {msgBox.opacity => 1.0 tween Interpolator.LINEAR}
     ]
 }

 def fadeOut = Timeline {
     keyFrames: KeyFrame {
         time: 1s
         values: msgBox.opacity => 0.0 tween Interpolator.LINEAR
         action: function() {delete msgBox from stage.scene.content}
     }
 }

 def stage = Stage {scene: Scene{}}

Code Sample 3: Using fadeIn- and fadeOut-animations to add and remove nodes.

Reference: Best Practices for JavaFX Mobile Applications & Best Practices for JavaFX Mobile Applications 2 from our JCG partner Michael Heinrichs at the Mike’s Blog.

Related Whitepaper:

Java Essential Training

Author David Gassner explores Java SE (Standard Edition), the language used to build mobile apps for Android devices, enterprise server applications, and more!

The course demonstrates how to install both Java and the Eclipse IDE and dives into the particulars of programming. The course also explains the fundamentals of Java, from creating simple variables, assigning values, and declaring methods to working with strings, arrays, and subclasses; reading and writing to text files; and implementing object oriented programming concepts. Exercise files are included with the course.

Get it Now!  

Leave a Reply


nine + = 18



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books