Java程序性能優化(c)

十四
對於boolean值,避免沒必要要的等式判斷express

  將一個boolean值與一個true比較是一個恆等操做(直接返回該boolean變量的值). 移走對於boolean的沒必要要操做至少會帶來2個好處:ide

  1)代碼執行的更快 (生成的字節碼少了5個字節);性能

  2)代碼也會更加乾淨 。ui

  例子:orm

  public class UEQ字符串

  {string

  boolean method (String string) {it

  return string.endsWith ("a") == true; // Violationio

  }form

  }

  更正:

  class UEQ_fixed

  {

  boolean method (String string) {

  return string.endsWith ("a");

  }

  }

  十5、對於常量字符串,用'String' 代替 'StringBuffer'

  常量字符串並不須要動態改變長度。

  例子:

  public class USC {

  String method () {

  StringBuffer s = new StringBuffer ("Hello");

  String t = s + "World!";

  return t;

  }

  }

  更正:

  把StringBuffer換成String,若是肯定這個String不會再變的話,這將會減小運行開銷提升性能。

  十6、用'StringTokenizer' 代替 'indexOf()' 和'substring()'

  字符串的分析在不少應用中都是常見的。使用indexOf()和substring()來分析字符串容易致使StringIndexOutOfBoundsException。而使用StringTokenizer類來分析字符串則會容易一些,效率也會高一些。

  例子:

  public class UST {

  void parseString(String string) {

  int index = 0;

  while ((index = string.indexOf(".", index)) != -1) {

  System.out.println (string.substring(index, string.length()));

  }

  }

  }

  參考資料:

  Graig Larman, Rhett Guthrie: "Java 2 Performance and Idiom Guide"

  Prentice Hall PTR, ISBN: 0-13-014260-3 pp. 282 – 283

  十7、使用條件操做符替代"if (cond) return; else return;" 結構

  條件操做符更加的簡捷

  例子:

  public class IF {

  public int method(boolean isDone) {

  if (isDone) {

  return 0;

  } else {

  return 10;

  }

  }

  }

  更正:

  public class IF {

  public int method(boolean isDone) {

  return (isDone ? 0 : 10);

  }

  }

  十8、使用條件操做符代替"if (cond) a = b; else a = c;" 結構

  例子:

  public class IFAS {

  void method(boolean isTrue) {

  if (isTrue) {

  _value = 0;

  } else {

  _value = 1;

  }

  }

  private int _value = 0;

  }

  更正:

  public class IFAS {

  void method(boolean isTrue) {

  _value = (isTrue ? 0 : 1); // compact expression.

  }

  private int _value = 0;

  }

相關文章
相關標籤/搜索