In this post I’m going to explore some examples of the approaches to reading HTTP responses in your BlackBerry Java application and how they can impact the application’s performance.
I realize that the performance of your HTTP-handling routines might not impose critical limitations to your application. But if you are considering ways to optimize these routines, I encourage you not only to take a look at these approaches, but also measure their performance characteristics in the context of your application.
The first approach, which I have successfully used in a commercial application, consists of reading the contents of the HTTP response one character at a time. Although slow, this approach is attractive because it is simple and does not require any HTTP-specific behavior from your code:
Reading the response data in bulk is a way to gain efficiency. However, this code relies on the underlying connection being able to provide the length of the response:
A version of the previous approach that I use in my KnowledgeBase application is this:
While the methods above produce a byte array and thus require a parsing or conversion step – omitted from the sample code – in order to deserialize the data, if your application has intimate knowledge of the response’s contents, you can use specialized methods of the DataInputStream class to read and deserialize the different values in the response in one step:
As you can see, the performance gains have a cost in the amount of complexity of your code and the knowledge of the response contents that your application should have. You will find that this is true for the approaches above as well as other approaches that exist. When deciding on one, consider the tradeoffs and always measure your gains before making a decision.