Performance
In general, performance is performed in the following ways:
- Execution speed
- Memory allocation
- Start time
- Load bearing capacity
Quantitative evaluation of the performance indicators:
- Execution time
- CPU Time
- Memory allocation
- Disk throughput
- Network throughput
- Response time
The level of tuning
- Design Tuning
- Code Tuning
- JVM Tuning
- Database tuning
- Operating system tuning
Performance tuning must have a clear goal, do not tune for tuning, if the current program does not have obvious performance problems, blindly adjust, the risk may be far greater than the benefits.
Design Optimization
1. Single-case mode
For critical components of the system and frequently used objects, using singleton mode can effectively improve the performance of the system.
2. Proxy mode
Proxy mode can be used to implement lazy loading, which improves the performance and responsiveness of the system.
In addition, you can consider how dynamic proxies are used. Dynamic agents are: The JDK comes with dynamic proxies, CGLIB, Javassist, or ASM libraries.
3. Enjoy meta mode
Benefits:
1) can save the overhead of duplicate object creation
2) reduced demand for system memory
4. Decorator Mode
Achieve a perfect separation of performance components from functional components
5. Observer mode
Observer mode can be used for event monitoring, notification, and other occasions. You can ensure that observers receive related messages and events in a timely manner without using polling monitoring.
6. Value Object Mode
Encapsulates the properties of an object, passing the encapsulated object over the network, thus enabling the system to have a better interaction model and reducing network communication data, thereby improving system performance.
7. Business Agent Model
Encapsulates a set of business processes that are composed of remote method calls, encapsulated in a proxy class that is located in the presentation layer.
Thinking:
What are the differences between the singleton mode, Factory mode and the enjoy meta mode?
commonly used optimization components and methods
1. Buffering
I/O operations can easily become a performance bottleneck, so add buffer components to the I/O read-write as much as possible to improve system performance.
2. Caching
Caches can save hard-won data or calculate results, and when they need to be reused, they can be obtained cheaply from the cache without the need to consume valuable system resources.
Java Cache Framework:
EHCache, Oscache,jbosscache
3. Object reuse--"pool"
The most familiar thread pool and database connection pool.
At present, the database connection pool component with more extensive application has c3p0 and Proxool.
4. Parallel substitution serial
5. Load Balancing
Cross-JVM virtual machines, specifically for distributed cache framework--terracotta, use Terracotta to enable Tomcat session sharing.
6. Time To change space
7. Space Change Time
Program Optimization
1. String optimization processing
1)
String str1 = "abc"; String str2 = "abc"; String str3 = new String ("abc"); System.out.println (STR1==STR2); TrueSystem.out.println (STR1==STR3); FalseSystem.out.println (Str1==str3.intern ()); True
2) memory leak of the subString () method
If the original string is long, the truncated string is shorter and is returned in the following way:
New String (Str1.substring (begin,end));
3) string segmentation and Lookup
You can use the method:
Split () Method--slowest, simple to do
StringTokenizer Method--faster, the general wording
IndexOf () and substring () method-fastest, trouble writing
Package Performance.program.string;import Java.util.stringtokenizer;public class Stringsplit {public static void Splitmethod (String str) {Long beginTime = System.currenttimemillis (); for (int i = 0; i < 10000; i++) {Str.split (";");} Long endTime = System.currenttimemillis (); SYSTEM.OUT.PRINTLN ("Splitmethod use" + (Endtime-begintime));} public static void Tokenizermethod (String str) {Long beginTime = System.currenttimemillis (); StringTokenizer st = new StringTokenizer (str, ";"); for (int i = 0, i < 10000; i++) {while (St.hasmoretokens ()) {st.nexttoken ();} st = new StringTokenizer (str, ";");} Long endTime = System.currenttimemillis (); SYSTEM.OUT.PRINTLN ("Tokenizermethod use" + (Endtime-begintime));} public static void Indexmethod (String str) {Long beginTime = System.currenttimemillis (); string tmp = str;for (int i = 0; i < 10000; i++) {while (true) {String splitstr = null;int j = tmp.indexof (";"); if (j<0) break;splitstr = tmp.substring (0,j); tmp = tmp.substring (j+1);} tmp = STR;} Long EndTime = System.currenttimemillis (); SYSTEM.OUT.PRINTLN ("Indexmethod use" + (Endtime-begintime));} /** * @param args */public static void main (string[] args) {//TODO auto-generated method stubstring orgstr = null; StringBuffer sb = new StringBuffer (); for (int i = 0; i <; i++) {sb.append (i); Sb.append (";");} Orgstr = Sb.tostring (); Splitmethod (ORGSTR); Tokenizermethod (ORGSTR); Indexmethod (ORGSTR);}}
4) Use Chartat instead of StartsWith and EndsWith
When performance requirements are high, you can use this one.
5) StringBuffer and StringBuilder
String result = "string" + "and" + "string" + "append";
This seemingly low-performance code actually executes faster than StringBuilder.
The reason is that the Java compiler itself optimizes.
However, it is not entirely dependent on compiler optimizations, or it is recommended to use StringBuffer or StringBuffer objects to improve system performance.
The differences between StringBuffer and StringBuilder are:
Stingbuffer almost all of the methods have been synchronized
StringBuilder does not have any synchronization.
So StringBuilder efficiency is better than stringbuffer, but in multithreaded systems, StringBuilder cannot guarantee thread safety.
In addition, pre-evaluation of the size of the StringBuilder can improve the performance of the system.
2. Core Data structures
1) List Interface
3 List implementations: ArrayList, vectors, and LinkedList
ArrayList and vectors use an array implementation, and most of the vectors are thread-synchronized, and ArrayList do not thread-sync any one method. (ArrayList and vectors look similar in performance)
The requirements for heap memory and GC are higher with LinkedList.
If the list object needs to frequently insert elements anywhere in the system application, you might consider using LinkedList instead of ArrayList
It is very efficient for ArrayList to remove elements from the tail, which is quite time consuming to remove elements from the head.
LinkedList is much more efficient at removing elements from the beginning, but it is very useful to remove elements from the middle.
|
Head |
Middle |
Tail |
| ArrayList |
6203 |
3125 |
16 |
| LinkedList |
15 |
8781 |
16 |
List Traversal operations
|
Foreach |
Iterators |
For loop |
| ArrayList |
63 |
47 |
31 |
| LinkedList |
63 |
47 |
Infinity |
2) Map Interface
The implementation classes are: Hashtable, HashMap, Linkedhashmap and TreeMap
The difference between HashTable and HashMap
HashTable Most methods are synchronized, HashTable does not allow the use of NULL values for key or value; (There is no apparent difference in performance)
3) Set Interface
4) Optimize the collection access code
1. Detach the code that is called repeatedly in the loop
for (int i=0;i<collection.size (); i++)
Replaced by
int count = Collection.size ();
for (int i=0;i<count;i++)
5). Randomaccess interface
3. Improve performance with NIO
In Java's standard I/O, stream-based I/O implementations, InputStream and OutputStream, are provided. This stream-based implementation processes data in bytes and makes it very easy to set up various filters.
NIO is the abbreviation for new I/O, as opposed to the old stream-based I/O method, which represents a newer set of Java I/O standards. is included in the JDK in Java 1.4, and features
-Provides buffer cache support for all original types
-Use Java.nio.charset.Charset as a character set encoding and decoding solution
-Increase channel objects (channels) as new raw I/O abstraction
-File access interface that supports lock and memory mapped files
-Provides asynchronous network I/O based on selector
Unlike streaming I/O, NIO is block-based, and it processes data in blocks as the base unit.
4. Reference type.
Strong references, soft references, weak references, and virtual references
Strong references:
A) A strong reference can directly access the target object
b) The object pointed to by a strong reference is not collected at any time by the system
c) Strong references can cause memory leaks
Soft references:
Soft references can be used through java.lang.ref.SoftReference. An object that holds soft references will not be recovered quickly by the JVM, and the JVM will determine when to recycle based on the current usage status. When the heap usage is near the threshold, the soft-referenced object is reclaimed. As long as there is enough memory, soft references may survive in memory for a relatively long period of time. Therefore, a soft reference can be used to implement a memory-sensitive cache.
Weak references:
In a system GC, objects are recycled whenever a weak reference is found, regardless of the adequacy of the system heap space.
Virtual reference
An object that holds a virtual reference is almost the same as no reference, and can be reclaimed by the garbage collector at any time. However, when trying to drop a strong reference by a virtual reference, the Get () method will always fail. Also, a virtual reference must be used in conjunction with a reference queue, which is designed to track the recycling process.
Weakhashmap class and its implementation
Weakhashmap is a typical application of weak references, which can be used as a simple caching table solution.
tips for improving system performance
1. Caution With exceptions
Try catch application and loop body
2. Using Local variables
The arguments passed when the method is called and the temporary variables created in the call are saved in the stack and are faster.
Other variables, such as static variables, instance variables, and so on, are created in the heap and are slower.
Local variables are accessed much faster than the class's member variables.
3. Bit operation instead of multiplication method
4. Replace switch.
This article should pay attention to a new thinking problem, the use of different ways to replace the switch statement.
Here's an example of performance testing, switch performance is better.
Package Com.oscar999.performance.skill;public class Switchreplaceskill {/** * @param args */protected void Oldmethod () {i NT RE = 0;for (int i = 0; i < 100000000; i++) {re = switchint (i);}} public void Newmethod () {int re=0;int[] sw= new int[]{0,3,6,7,8,10,16,18,44};for (int i = 0; i < 100000000; i++) {re = a Rrayint (Sw,i);}} protected int switchint (int z) {int i = z% + 1;switch (i) {case 1:return 3;case 2:return 6;case 3:return 7;case 4:retu RN 8;case 5:return 10;case 6:return 16;case 7:return 18;case 8:return 44;default:return-1;}} protected int Arrayint (int[] Sw,int z) {int i=z%10+1;if (i>8| |i<1) {return-1;} Else{return sw[i];}} public static void Main (string[] args) {//TODO auto-generated method Stubswitchreplaceskill skill = new Switchreplaceskil L (); Long begtime = System.currenttimemillis (); Skill.oldmethod (); Long endTime = System.currenttimemillis (); System.out.println ("Old Method use:" + (Endtime-begtime)); begtime = System.currenttimemillis (); Skill.newmethod (); EndTime = SystEm.currenttimemillis (); System.out.println ("New Method use:" + (Endtime-begtime));}}
5. One-dimensional arrays instead of two-dimensional arrays
See examples directly:
Package Com.oscar999.performance.skill;public class Onedime2twodime {protected void Oldmethod () {int[][] array = new int[ 1000][1000];int re = 0;for (int k=0;k<100;k++) for (int. i=0;i<array[0].length;i++) for (int j=0;j<array[0].len gth;j++) Array[i][j] = i;for (int k=0;k<100;k++) for (int. i=0;i<array[0].length;i++) for (int j=0;j<array[0 ].length;j++) re=array[i][j];} protected void Newmethod () {int[] array = new Int[1000000];int re = 0;for (int k=0;k<100;k++) for (int I=0;i<array.leng th;i++) Array[i] = i;for (int k=0;k<100;k++) for (int i=0;i<array.length;i++) re = Array[i];} /** * @param args */public static void main (string[] args) {//TODO auto-generated method stubonedime2twodime skill = new Onedime2twodime (); Long begtime = System.currenttimemillis (); Skill.oldmethod (); Long endTime = System.currenttimemillis (); System.out.println ("Old Method use:" + (Endtime-begtime)); begtime = System.currenttimemillis (); Skill.newmethod (); EndTime = System.currenttimemillis(); System.out.println ("New Method use:" + (Endtime-begtime));}}Old Method use:453
New Method use:281
One-dimensional numbers use a lot less time.
6. Extracting An expression
Some of the repetitive operations can be extracted.
Package Com.oscar999.performance.skill;public class Extraexpression {protected void Oldmethod () {Double d = math.random ( );d ouble a = Math.random ();d ouble B = math.random ();d ouble e = math.random ();d ouble x,y;for (int i=0;i<10000000;i++) {x = D*a*b/3*4*a;x = E*a*b/3*4*a;}} protected void Newmethod () {Double d = math.random ();d ouble a = Math.random ();d ouble B = math.random ();d ouble e = Math.rand Om ();d ouble x,y,t;for (int i=0;i<10000000;i++) {t = a*b/3*4*a;x = D*t;x = E*t;}} /** * @param args */public static void main (string[] args) {//TODO auto-generated method stubonedime2twodime skill = new Onedime2twodime (); Long begtime = System.currenttimemillis (); Skill.oldmethod (); Long endTime = System.currenttimemillis (); System.out.println ("Old Method use:" + (Endtime-begtime)); begtime = System.currenttimemillis (); Skill.newmethod (); EndTime = System.currenttimemillis (); System.out.println ("New Method use:" + (Endtime-begtime));}}
Old Method use:109
New Method use:79
7. Expand Loops
Expansion loops are an optimization method that is used in extreme situations, because the unfolding may affect the readability and maintainability of the code, so the trade-offs are based on the actual situation.
See Example:
Package Com.oscar999.performance.skill;public class Expandcycle {protected void Oldmethod () {int[] array = new int[ 9999999];for (int i=0;i<9999999;i++) {array[i]=i;}} protected void Newmethod () {int[] array = new int[9999999];for (int i=0;i<9999999;i+=3) {array[i]=i;array[i+1]=i+1; array[i+2]=i+2;}} /** * @param args */public static void main (string[] args) {//TODO auto-generated method stubexpandcycle skill = new Expa Ndcycle (); Long begtime = System.currenttimemillis (); Skill.oldmethod (); Long endTime = System.currenttimemillis (); System.out.println ("Old Method use:" + (Endtime-begtime)); begtime = System.currenttimemillis (); Skill.newmethod (); EndTime = System.currenttimemillis (); System.out.println ("New Method use:" + (Endtime-begtime));}}
Old Method use:78
New Method use:47
8. Boolean operations instead of bitwise operations
Although bit operations are much faster than arithmetic operations, using bitwise operations instead of Boolean operations is a very bad choice when it comes to conditional judgment.
For "A&&b&&c", the entire expression returns false whenever there is a return of false.
Package Com.oscar999.performance.skill;public class Booleanbit {protected void Oldmethod () {Boolean A = False;boolean B = t Rue;int d = 0;for (int i=0;i<10000000;i++) if (a&b& "Java_perform". Contains ("Java")) d = 0;} protected void Newmethod () {Boolean A = False;boolean b = True;int d = 0;for (int i=0;i<10000000;i++) if (a&&b& & "Java_perform". Contains ("Java")) d = 0;} /** * @param args */public static void main (string[] args) {//TODO auto-generated method stubbooleanbit skill = new Boole Anbit (); Long begtime = System.currenttimemillis (); Skill.oldmethod (); Long endTime = System.currenttimemillis (); System.out.println ("Old Method use:" + (Endtime-begtime)); begtime = System.currenttimemillis (); Skill.newmethod (); EndTime = System.currenttimemillis (); System.out.println ("New Method use:" + (Endtime-begtime));}}
Old Method use:265
New Method use:32
9. Using ArrayCopy ()
The Java API improves the efficient method of array replication: ArrayCopy ().
This function is the native function, usually the performance of the native function is better than the normal function, only for performance reasons, in software development, should call the native function whenever possible.
package Com.oscar999.performance.skill;public class ArrayCopy {protected void Oldmethod () {int size = 100000;int[] Array = new int[size];int[] Arraydst = new Int[size];for (int i=0;i<array.length;i++ ) {array[i]=i;} for (int k=0;k<1000;k++) for (int i=0;i<size;i++) arraydst[i]=array[i];} protected void Newmethod () {int size = 100000;int[] Array = new int[size];int[] Arraydst = new Int[size];for (int i=0;i<a rray.length;i++) {array[i]=i;} for (int k=0;k<1000;k++) system.arraycopy (array, 0, ARRAYDST, 0, size);} /** * @param args */public static void main (string[] args) {//TODO auto-generated method stubarraycopy skill = new ARRAYC Opy (); Long begtime = System.currenttimemillis (); Skill.oldmethod (); Long endTime = System.currenttimemillis (); System.out.println ("Old Method use:" + (Endtime-begtime)); begtime = System.currenttimemillis (); Skill.newmethod (); EndTime = System.currenttimemillis (); System.out.println ("New Method use:" + (Endtime-begtime));}}
Old Method use:156
New Method use:63
10. Using Buffer for I/O operations
In addition to NIO, there are two basic ways to use Java for I/O operations
1. Using InputStream and Outoutstream-based methods
2. Using writer and reader
Regardless of the way you use file I/O, if you can use buffering properly, you can effectively improve I/O performance
Package Com.oscar999.performance.skill;import Java.io.bufferedoutputstream;import Java.io.dataoutputstream;import Java.io.fileoutputstream;public class Bufferstream {protected void Oldmethod () {int count = 10000;try {DataOutputStream d OS = new DataOutputStream (New FileOutputStream ("testfile.txt")), for (int i = 0; i < count; i++) dos.writebytes (String.va Lueof (i) + "\ r \ n");d os.close (); catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();}} protected void Newmethod () {int count = 10000;try{dataoutputstream dos = new DataOutputStream (New Bufferedoutputstream ( New FileOutputStream ("Testfile.txt"))); for (int i = 0; i < count; i++) dos.writebytes (string.valueof (i) + "\ r \ n");d OS.C Lose ();} catch (Exception e) {e.printstacktrace ();}} /** * @param args */public static void main (string[] args) {//TODO auto-generated method Stubbufferstream skill = new Buf Ferstream (); Long begtime = System.currenttimemillis (); Skill.oldmethod (); Long endTime = System.currenttimemillis (); System.ouT.println ("Old Method use:" + (Endtime-begtime)); begtime = System.currenttimemillis (); Skill.newmethod (); endTime = Syst Em.currenttimemillis (); System.out.println ("New Method use:" + (Endtime-begtime));}}
Old Method use:516
New Method use:0
11. Use Clone () instead of new
For heavyweight objects, better than objects may make some complex and time-consuming operations in the constructor, so the constructors may take longer to execute. The Object.clone () method can quickly replicate an object instance by bypassing the object constructor. Because you do not need to call the object constructor, the Clone method is not affected by the performance of the constructor and generates an instance quickly.
12. Static method Substitution instance method
The method described with the static keyword is static, and in Java, better than an instance method requires maintaining a structure similar to a virtual function table for polymorphic support. The invocation of an instance method requires more resources than a static method. Therefore, for some commonly used tool class methods, there is no need to overload them, so declaring them as static can speed up the invocation of the method.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Java Performance Optimization Series 1[design and program Optimization]