首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 计算机考试 > 认证考试 > JAVA认证 >

Java代码的优化策略(3)

2009-06-25 
本文是影响Java性能的代码和优化方法

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

  }

  }

  优化为:

  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 Component positions…

  for( int i = 0; i < componentArray.length; i++ ) {

  Point position = componentArray[i].getPosition( );

  // Process position value…

  // Note: A Point object is created for each iteration

  // of the loop…

  }

  可再次优化,仅使用一个类对象:)

  public

  class Component

  {

  private int x;

  private int y;

  public Point getPosition( Point rv )

  {

  if( rv == null) rv = new Point( );

  rv.x = x; // update its state

  rv.y = y;

  return rv;

  }

  // Create a single point object and reuse it…

  Point p = new Point( );

  for( int i = 0; i < componentArray.length; i++ ) {

  Point position = componentArray[i].getPosition( p );

  // Process position value…

  // Note: Only one Point object is ever created.

  }

  13. J2EE相关

  a) 尽量不要将大对象放到HttpSession或其他须序列化的对象中,并注意及时清空Session

  b) 使用预编译语句prepareStatement代替createStatement

  c) 尽可能使用连接池

  d) 能使用Cache就使用Cache,具体实现可参考jive(CacheCacheableCacheObjectCacheSizesDefaultCacheLinkdListLinkdListNode)或ofbiz(org.ofbiz.core.util. UtilCache.Java)

 

3COME考试频道为您精心整理,希望对您有所帮助,更多信息在http://www.reader8.net/exam/

热点排行