Wicket page size
One of the most important things you need to keep an eye on when developing Wicket apps is the page size. Not the size of the HTML that is sent to the browser, we are talking about the size of all the models, objects, and classes that Wicket creates.
All of these objects get serialized into session when the Page version is saved; such as when you update something on the page via an AJAX request. The impact is exaggerated when you are using a session provider such as Redis, which requires network round-trips.
Reducing page size using Literals
There are many techniques we can use to reduce page size. We will discuss one here which is the Literal Component that can be used in place of Labels:
public class Literal extends Component {
private static final long serialVersionUID = 1L;
private transient String lbl;
public Literal(String id, String lbl) {
super(id);
this.lbl = lbl;
}
@Override
public void onConfigure() {
super.onConfigure();
setEscapeModelStrings(false);
setRenderBodyOnly(true);
}
@Override
protected void onRender() {
if(!StringUtils.isBlank(lbl)) {
getResponse().write(lbl);
}
}
}
You can see that Literal relies on a transient String which never gets serialized and it creates no other components. It simply writes the String to the response body without needing to store a Model. A Label, whether you pass a String or a Model, needs to store a Model.
How to observe the difference in page size
We can easily create a test page to observe this difference in page size. I won’t include the full code here, but you can see it on GitHub. We create a page with a ListView that renders 100 items, each displaying a random String of 100 characters.
Results:
Label with Model: 101 KB
Label with LoadableDetachableModel: 54 KB
Literal: 48 KB
When to use Literal
Literals are good for replacing Label’s inside of ListView’s or in any place that requires a dynamic String to be displayed that doesn’t need to be updated via AJAX.
You will still need to use Label’s when doing AJAX updates because a Literal doesn’t create any Components or Model objects and only renders it’s transient value during page render.
However there are a lot more use cases for Literal that will net you even more size savings. You can replace BookmarkableLink’s, Images, etc. Of course you should use Literal’s sparingly only when you’re dealing with large pages where performance is critical.
Good luck reducing your Wicket page sizes! I will blog about other ways to do it in the future.