Share a few efficient USES of Java to improve performance

  • 2020-04-01 03:32:45
  • OfStack

1. In important loops, eliminate the method call when the loop terminates


for(int i=0; i<collection.size(); i++)
{
...
}
for(int i=0; i<collection.size(); i++)
{
...
}

Replace with...


view plaincopy to clipboardprint?
for(int i=0;n=collection.size();i<n;i++)
{
...
}

2. Generally, move those that are not related to the loop index to the outside of the loop


for(int i=0;terminal=x.length;i<terminal;i++){
 X[i]=x[i]/scaleA*scaleB;
}
for(int i=0;terminal=x.length;i<terminal;i++){
X[i]=x[i]/scaleA*scaleB;
}

Instead of


double scale = scaleB/scaleA;
for(int i=0; terminal=x.length; i<terminal; i++){
 X[i]=x[i]*scale;
}

2. The string

Eliminate string concatenation
When creating long strings, always use StringBuffter instead of String
Pre-allocate the StringBuffer space

StringBuffer sb = new StringBuffer (5000);

3. Basic data types

Use basic data types in important loops (int data is usually faster than long/double data)
The wrapper class for primitive data types (Boolean, Integer, etc) is used primarily when the method argument passed must be a reference to an object (rather than a primitive data type)
Use the static final modifier for all constant algebraic expressions

Make constants easier to reference (the compiler preevaluates constant expressions)

Abnormal 4.

Exceptions are only used for a single true error condition

Throwing an exception and executing a catch block of code can be costly (mainly because it takes a snapshot of the thread stack when an exception is created)
An exception is thrown only when the condition is truly exceptional

Optimize the compiler and runtime by putting several method calls into a single try/catch block instead of implementing several try/catch blocks for each method call

Benchmark 5.

Note that all of these techniques vary from platform to platform and virtual machine to virtual machine

For example, in some servlet containers, it is faster to output bytes through an OutputStream
A PrintWriter is faster to output characters in other containers

These tips describe the most portable recommendations

You may need to run some benchmarks to determine what is the fastest on your platform


Related articles: