Skip to content

Instantly share code, notes, and snippets.

@warrenrentlytics
Last active August 15, 2018 21:32
Show Gist options
  • Save warrenrentlytics/42b1130d5189b7c91f7dbfdea386e142 to your computer and use it in GitHub Desktop.
Save warrenrentlytics/42b1130d5189b7c91f7dbfdea386e142 to your computer and use it in GitHub Desktop.
Shows a faster, better way of updating a set of string labels. The comments have a slower version that completely redraws the screen and is massively slower: > 30 ms vs 0-2 ms
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
public class JavaFXLayoutTimingTest extends Application {
private static Instant start;
private int reloadCount = 0;
private final int pageSize = 50;
private List<Label> labels = new ArrayList<>(pageSize);
private void logTimeSinceStart() {
System.err.println("Reloaded label strings: " + Duration.between(start, Instant.now()).toMillis());
}
/*
about 35 ms to run this!
public void reloadEntireStage(Stage stage) {
System.err.println("Reloading page at " + Instant.now());
start = Instant.now();
root = new VBox();
Button button = new Button("I am a banana");
List<Label> labels = new ArrayList<>(pageSize);
for(int i = 1; i <= pageSize; i++) {
labels.add(new Label("Label " + (reloadCount*pageSize + i)));
}
root.getChildren().add(button);
root.getChildren().addAll(labels);
button.setOnAction(ae -> {
reloadCount++;
reloadEntireStage(stage);
});
scene.setRoot(root);
stage.setScene(scene);
}
*/
/* 0-2 milliseconds to run this!!! */
private void updateLabelStrings() {
start = Instant.now();
final int pageSize = 50;
start = Instant.now();
for (int i = 0; i < pageSize; i++) {
labels.get(i).setText("Label " + (reloadCount * pageSize + i));
}
logTimeSinceStart();
}
@Override
public void start(Stage stage) {
stage.setTitle("Web View");
VBox root = new VBox();
Button button = new Button("I am a banana");
Scene scene = new Scene(root, 400, 900);
scene.setOnKeyPressed(event -> {
switch (event.getCode()) {
case LEFT:
reloadCount--;
updateLabelStrings();
break;
case RIGHT:
reloadCount++;
updateLabelStrings();
break;
}
});
root.getChildren().add(button);
root.getChildren().addAll(labels);
button.setOnAction(ae -> {
reloadCount++;
updateLabelStrings();
});
for (int i = 0; i < pageSize; i++) {
labels.add(new Label("Label " + (reloadCount * pageSize + i)));
}
root.getChildren().addAll(labels);
scene.setRoot(root);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
start = Instant.now();
launch(args);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment