Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java Performance 1.2 Perspective. Optimization Guidelines Get working code Use profiler Optimize important code paths Ensure you don’t add bugs while.

Similar presentations


Presentation on theme: "Java Performance 1.2 Perspective. Optimization Guidelines Get working code Use profiler Optimize important code paths Ensure you don’t add bugs while."— Presentation transcript:

1 Java Performance 1.2 Perspective

2 Optimization Guidelines Get working code Use profiler Optimize important code paths Ensure you don’t add bugs while improving performance

3 Tools Commercial Code Profilers –OptimizeIt –Jprobe –Embedded tools in IDEs

4 Components Changed for 1.2 Compiler Class Library Run Time Support

5 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.

6 Class Libraries String class – hashcode() Non synchronized collection classes SoftReference ThreadLocal

7 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

8 Optimizations not done Extracting non-variant statements from loops –Common in some other languages (C++, Fortran) Optimizing arithmetic expressions –Also common in other languages

9 Loop Optimization When possible, place loop in try block, not other way Place object or static references in local variables

10 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

11 AbstractList modCount –Allows iterations to fail as soon as list modified –Preferable to unpredictable behavior

12 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

13 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

14 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

15 Optimization Guidelines Get working code Use profiler Optimize important code paths Ensure you don’t add bugs while improving performance

16 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

17 Code Comparisons Verify clock –Granularity 1 ms on Sparc systems –Granularity as high as 55 ms Windows 1 millisecond on platform used here

18 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

19 Clock Verification Testing Clock Elapsed:3000 Iterations: Time values:2997

20 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

21 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(); }

22 NumberFormat vs Format(), cont DecimalFormat – 99/46msec* Inline format() 27/8 msec format() 43/9 msec *1.1.6 time/1.2.2 time

23 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

24 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

25 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);

26 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() );

27 StringBuffer “+” operation with constants –11578/1802 StringBuffer reused –9301/2536 “+” mixed constants, vars –17050/3322

28 Instanceof vs cast instanceof if ( objectReference instanceof Classname) Try-catch Try { or = (Classname) objectReference; } Catch( ClassCastException cce ) { }

29 Instanceof vs cast Not much different if few Exceptions thrown Big difference if many exceptions thrown –instanceof much faster

30 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 )

31 Synchronization Synched method –6279/1066 Synched block –6201/1232 No synch –950/753

32 Stack variables vs instance, static Very little difference in tests

33 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

34 Collection spanning Iterator ListIterator Enumeration Get method

35 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

36 Object Instantiation Depth of class hierarchy Other objects contained in the object Native components (AWT) –Lightweight –Heavyweight

37 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

38 Object Instantiation 3 Lazy construction –Delay construction of parts until needed –Construct parts in another thread

39 Additional Classes New to 1.2 Not necessarily Improved Performance Better programming interfaces for easier implementations Better support for local caching of remote data

40 Additional Classes New to 1.2 ThreadLocal Comparable Reference Classes Collection

41 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

42 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.

43 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 }

44 Collections Collections of various types –Ordered, unordered –Some limit the entries Hashtable inhibits duplicate keys –Can be synchronized, or not, as apropos

45 Reference Classes Reference Weak Reference Soft Reference Phantom Reference

46 Reference Classes, cont. Reference –Base class for reference classes Weak reference –Does not inhibit garbage collection and finalization –Used in Threadlocal via WeakHashmap

47 Reference Classes, cont. Soft Reference –Will be collected only if memory REALLY needed –Use for caching data PhantomReference –Reference on a ReferenceQueue

48 Collection Classes Collection –Vector, ArrayList SortedSet –TreeSet Set –HashSet

49 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.

50 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


Download ppt "Java Performance 1.2 Perspective. Optimization Guidelines Get working code Use profiler Optimize important code paths Ensure you don’t add bugs while."

Similar presentations


Ads by Google