}
public void flushCache()
{
System.out.println (“Clearing cache”);
data.clear();
}
public static void main (String[] args)
{
DataServer ds = new DataServer();
int count = 0;
while (true) // infinite loop for test
ds.get (“” count+);
}
}
Java代码优化策略(3)
时间:2011-10-16
8. Lazy Loading (Lazy evaluation)在需要装入的时候才装入
static public long
factorial( int n ) throws IllegalArgumentException
{
IllegalArgumentException illegalArgumentException =
new IllegalArgumentException( “ must be >= 0” );
if( n < 0 ) {
throw illegalArgumentException ;
} else if( ( n 0 ) || ( n 1 ) ) {
return( 1 );
} else (
return( n * factorial( n – 1 ) ) ;
}
优化后代码
static public long
factorial( int n ) throws IllegalArgumentException
{
if( n < 0 ) {
throw new IllegalArgumentException( “must be >= 0” );
} else if( ( n 0 ) || ( n 1 ) ) {
return( 1 );
} else (
return( n * factorial( n – 1 ) ) ;
}
9. 异常在需要抛出的地方抛出,try catch能整合就整合
try {
some.method1(); // Difficult for javac
} catch( method1Exception e ) { // and the JVM runtime
// Handle exception 1 // to optimize this
} // code
try {
some.method2();
} catch( method2Exception e ) {
// Handle exception 2
}
try {
some.method3();
} catch( method3Exception e ) {
// Handle exception 3
}
已下代码 更容易被编译器优化
try {
some.method1(); // Easier to optimize
some.method2();
some.method3 ();
} catch( method1Exception e ) {
// Handle exception 1
} catch( method2Exception e ) {
// Handle exception 2
} catch( method3Exception e ) {
// Handle exception 3
}
Java代码优化策略(4)
时间:2011-10-16
10. For循环的优化
Replace…
for( int i = 0; i < collection.size(); i++ ) {
...
}
with…
for( int i = 0, n = collection.size(); i < n; i++ ) {
...
}
11. 字符串操作优化
在对字符串实行+操作时,最好用一条语句
// Your source code looks like…
String str = “profit = revenue( ” revenue
“ – cost( ” cost ““;
// 编译方法
String str = new StringBuffer( ).append( “profit = revenue( “ ).
append( revenue ).append( “ – cost( “ ).
append( cost ).append( ““ ).toString( );
在循环中对字符串操作时改用StringBuffer.append()方法
String sentence = “”;
for( int i = 0; i < wordArray.length; i++ ) {
sentence += wordArray[ i ];
}
优化为
StringBuffer buffer = new StringBuffer( 500 );
for( int i = 0; i < wordArray.length; i++ ) {
buffer.append( wordArray[ i ] );
}
String sentence = buffer.toString( );
12. 对象重用(特别对于大对象来说)
public
class Point
{
public int x;
public int y;
public Point( )
{
this( 0, 0 );
}
}
Java代码优化策略(5)
时间:2011-10-16
优化为:
public class Component
{
private int x;
private int y;
public Point getPosition( )
{
Point rv = new Point( ); // Create a new Point
rv.x = x; // Update its state
rv.y = y;
return rv;
}
}
// Process an array of
|