Java Performance 1.2 Perspective
Optimization Guidelines • Get working code • Use profiler • Optimize important code paths • Ensure you don’t add bugs while improving performance
Tools • Commercial Code Profilers • OptimizeIt • Jprobe • Embedded tools in IDEs
Components Changed for 1.2 • Compiler • Class Library • Run Time Support
Compiler • -O option is now meaningless • Optimization under JDK 1.2 essentially not done • Successive quoted strings adjoining the same “+” operator combined at least sometimes.
Class Libraries • String class – hashcode() • Non synchronized collection classes • SoftReference • ThreadLocal
Runtime support • JVMs now do inlining • Different from javac –O • Retains implemented method structure in exceptions • Heuristic analysis allows more precise targeting of byte code to be compiled to native
Optimizations not done • Extracting non-variant statements from loops • Common in some other languages (C++, Fortran) • Optimizing arithmetic expressions • Also common in other languages
Loop Optimization • When possible, place loop in try block, not other way • Place object or static references in local variables
Inline Code • Not done by javac in 1.2 • Can be done by jit or HotSpot • Private, final and/or static methods • Usually must be short, such as simple getters, setters
AbstractList • modCount • Allows iterations to fail as soon as list modified • Preferable to unpredictable behavior
ArrayList vs Vector • Vector • Specify initial, increment, for size • Threadsafe via synchronization • ArrayList • Specifiy initial only, increments by 50% • Not threadsafe, but faster • 1.2 Synchronization takes about 25% time 1.1.6
Implementing Caches • Storing data retrieved from other systems • Use if available • Obtain if missing • SoftReference • Keeps data available • Until memory really needed by jvm • A combination of hard and soft references could be used; Only soft references could be freed
Synchronization • Method synchronization • Synchronized blocks • Method synchronization faster, code smaller • Bit set in method descriptor • Overhead significantly reduced in 1.2 • Static method synchronization done on Class object
Optimization Guidelines • Get working code • Use profiler • Optimize important code paths • Ensure you don’t add bugs while improving performance
Java byte code • javap – tool to display byte code • Similar to options on C, COBOL, PL/1, Fortran to display assembler code generated • javap –c com.edwardjones.xxx.Classname >Classname.bc
Code Comparisons • Verify clock • Granularity 1 ms on Sparc systems • Granularity as high as 55 ms Windows • 1 millisecond on platform used here
Code to verify clock long numberDifferentTimes = 0; long iterations = 0; long startTime = System.currentTimeMillis(); long lastTime = startTime; long endGoal = startTime+3000; // test for 3 seconds while ( ( endTime = System.currentTimeMillis() ) < endGoal ){ if ( endTime != lastTime ){ lastTime = endTime; numberDifferentTimes++; } iterations ++; } System.out.println("Elapsed:"+(endTime-startTime)); System.out.println("Iterations:"+iterations); System.out.println("Time values::"+numberDifferentTimes); } // on Sparc systems, iterations = approx 3000 // On windows systems, may be as low as 60
Clock Verification Testing Clock Elapsed:3000 Iterations:2046412 Time values:2997
For Each Enquiry • Determine number of iterations to get performance perspective • Execute several times in succession • Execute several different times of day to ensure correct report
NumberFormat vs Format() static String format( int value, int digits ) { StringBuffer sb = new StringBuffer(); sb.append( Integer.toString( value ) ); int i1 = sb.length(); for( int ix = i1; ix < digits ; ix++ ) { sb.insert( 0, '0' ); } return sb.toString(); }
NumberFormat vs Format(), cont • DecimalFormat – 99/46msec* • Inline format() 27/8 msec • format() 43/9 msec • *1.1.6 time/1.2.2 time
SimpleDateFormat vs Log Reqs • Log entries written 1000s of times per day • Date format fixed • DateFormat 835/343 msec • optimized: 170/56 • Optimized to form yyyy-mm-dd-hh.mm.ss.mmm
Vector vs ArrayList • Vector Synchronized, ArrayList not • Vector has overhead of synchronization for almost all methods • ArrayList more suitable for objects which need no synchronization • Either because they do not change • Servlets may not expose some collections outside primary thread
StringBuffer vs String “+” • “+” operator (and “+=“) implicitly build a StringBuffer • 1 StringBuffer created String s=“A”+1+a.method()+”C”+Integer.toString(3); • StringBuffer created for each statement String s = “A”+1; s+=a.method(); s+=“C”; s+=Integer.toString(3);
StringBuffer vs String “+” (cont) • Readability may demand “+” • throw new Exception( “Error recorded in line “ + StaticUtils.getLineNumber( “%C%” ) + “ while performing Tuxedo service “+tuxServiceName); • Preferred to • StringBuffer sb = new StringBuffer(); • sb.append(“Error recorded in line “ ); • sb.append(StaticUtils.getLineNumber( “%C%” ) ); • sb.append(“ while performing Tuxedo service “); • sb.append(tuxServiceName ); • throw new Exception( sb.toString() );
StringBuffer • “+” operation with constants • 11578/1802 • StringBuffer reused • 9301/2536 • “+” mixed constants, vars • 17050/3322
Instanceof vs cast • instanceof if ( objectReference instanceof Classname) • Try-catch Try { or = (Classname) objectReference; } Catch( ClassCastException cce ) { }
Instanceof vs cast • Not much different if few Exceptions thrown • Big difference if many exceptions thrown • instanceof much faster
What if class type specified at execution? • Use methods in java.lang.Class • Can objects of class class1 be referenced as type class2? • class2.isAssignableFrom( Class class) • Is an object an instance of class class1? • class1.isInstance( Object o )
Synchronization • Synched method • 6279/1066 • Synched block • 6201/1232 • No synch • 950/753
Stack variables vs instance, static • Very little difference in tests
Garbage Collection • Never guaranteed to be executed • System.gc() requests garbage collection • Algorithm is implementation dependent • Runs when all other threads held • Quick check to free some storage • May take longer if significant deficiency • Complicated by new java.lang.ref classes
Collection spanning • Iterator • ListIterator • Enumeration • Get method
Immutable Objects • Can be implemented for any application • No need to worry about data changing • String, base type wrapper classes immutable • Characteristics: • Class final • No setter, only getter methods • All data private • All data defined in constructor
Object Instantiation • Depth of class hierarchy • Other objects contained in the object • Native components (AWT) • Lightweight • Heavyweight
Object Instantiation 2 • Allocate memory from heap for all class variables, base types, references • Instance variables inited to default value • Run init block for constructor about to execute • Performed in order subclass backward to Object • Avoid multiple initializations
Object Instantiation 3 • Lazy construction • Delay construction of parts until needed • Construct parts in another thread
Additional Classes New to 1.2 • Not necessarily Improved Performance • Better programming interfaces for easier implementations • Better support for local caching of remote data
Additional Classes New to 1.2 • ThreadLocal • Comparable • Reference Classes • Collection
ThreadLocal • New in JDK 1.2 • Like Hashtable • Key is implicitly Thread.currentThread() • Method to build instances when subclassed • Reference classes allow this to work • WeakReference used
Comparable • compareTo(Object o) • Previously implemented as method only • Following must be true: • oref1.compareTo(oref2)==Oref2.compareTo(oref1) • May be a problem if oref1 and oref2 are not of exactly the same class • One may recognize different classes, other may not.
Comparable (cont.) Public int compareTo( Object o ) { If ( this.getClass() != o.getClass() ) { // NullPointerException for “o” may be thrown throw new ClassCastException( “message”); } // … rest of compare }
Collections • Collections of various types • Ordered, unordered • Some limit the entries • Hashtable inhibits duplicate keys • Can be synchronized, or not, as apropos
Reference Classes • Reference • Weak Reference • Soft Reference • Phantom Reference
Reference Classes, cont. • Reference • Base class for reference classes • Weak reference • Does not inhibit garbage collection and finalization • Used in Threadlocal via WeakHashmap
Reference Classes, cont. • Soft Reference • Will be collected only if memory REALLY needed • Use for caching data • PhantomReference • Reference on a ReferenceQueue
Collection Classes • Collection • Vector, ArrayList • SortedSet • TreeSet • Set • HashSet
Class file optimizers • Reduce constants pool size • Remove unused methods • May not work for libraries, will for applications • Inline static methods, final methods, or private methods.
Total Performance Perspective • GUI Builders and Debuggers • Combine cost to develop, support, execute • Reputedly slower code than “hand coded” • Cheaper development costs • Vs cost of server boxes