WebReference.com - Chapter 16 of Java Servlets Developer's Guide, from Osborne/McGraw-Hill (1/4)
[next] |
Java Servlets Developer's Guide
Performance Tips and Tricks
In This Chapter:
|
In this, the final chapter, we'll take a look at some general tips to maintain good performance when writing servlets. I will not attempt to quantify any of these suggestions; there are such a wide variety of processors and Virtual Machines that trying to compare performance timings can be very misleading. Keep in mind that as VMs continue to improve and processors continue to get faster, the overall relevance of the following tips may diminish. Even so, coding for performance will pay off in the long run, especially when creating servlets that will be used by hundreds, or even thousands, of concurrent users. Even small gains in performance can provide huge gains in scalability.
Avoid String Concatenation
Even though I've used String concatenation throughout this book, mostly to improve readability, you should try to avoid this habit and use a StringBuffer instead. For example, the following:
String a = "Hello ";
String b = "Karl";
String c = a + b;
should be replaced with this:
String a = "Hello";
String b = "Karl";
StringBuffer sb = new StringBuffer(a);
sb.append(b);
String c = sb.toString();
String concatenation results in a new String and StringBuffer instance to be created by the Virtual Machine and reassigned to the new String value; each old String is released for garbage collection, resulting in many short-lived objects. Note that this is not true for String literals; the compiler will optimize "Hello " + "Karl" as "Hello Karl" automatically.
Also, if you have a good idea of how large the final String may be, you can also preallocate the size of the StringBuffer by using a different constructor:
StringBuffer sb = new StringBuffer(256);
A very nice feature of the StringBuffer class is that the append() method returns the StringBuffer instance, so you can cascade the append() calls:
StringBuffer sb = new StringBuffer();
sb.append("Hello ").append("Karl");
[next] |
Created: July 31, 2002
Revised: July 31, 2002
URL: https://webreference.com/programming/java/servletsguide/