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
}
10. For循环的优化
Replace…
for( int i = 0; i < collection.size(); i++ ) {
...
}
with…
for( int i = 0, n = collection.size(); i < n; i++ ) {
...
}