Java異常的性能分析(2)

發表于:2014-03-31來源:不祥作者:Java譯站點擊數: 標簽:java
{ if ( i == 0 ) sign = 1; //sign at first position else return str; //otherwise it is not numeric } else //non-numeric return str; } //cast to int if value is in int range if ( res Integer.MAX_VALUE )

  {

  if ( i == 0 )

  sign = 1; //sign at first position

  else

  return str; //otherwise it is not numeric

  }

  else //non-numeric

  return str;

  }

  //cast to int if value is in int range

  if ( res < Integer.MAX_VALUE )

  return ( int ) res * sign;

  //otherwise return Long

  return res * sign;

  }

  很驚訝吧,新的方法解析數字比JDK的實現快多了!很大一個原因是因為JDK在解析的最后,調用了一個支持的解析方法,像這樣:

  public static int parseInt( String s, int radix ) throws NumberFormatException

  新的方法和舊的相比(注意方法調用的次數——對于非數字串pack只調用了1百萬次,而別的情況能調用到千萬級別):

  Pack: Made 100.000.000 iterations for string '12345' : time = 12.145 sec

  Pack: Made 1.000.000 iterations for string '12345a' : time = 23.248 sec

  strToObject: Made 100.000.000 iterations for string '12345' : time = 6.311 sec

  strToObject: Made 100.000.000 iterations for string '12345a' : time = 5.807 sec

  總結

  千萬不要把異常當成返回碼一樣用,或者當作可能發生的事件(尤其是和IO無關的方法)往外拋。拋異常的代價太昂貴了,對于一般的方法,至少要慢百倍以上。

  如果你每條數據都需要解析,又經常會出現非數值串的時候,盡量不要用Number子類型的parse*/valueOf這些方法。為了性能考慮,你應當手動解析它們。

  原創文章轉載請注明出處:Java異常的性能分析

原文轉自:http://it.deepinmind.com/java/2014/03/25/java-exception-performance.html

国产97人人超碰caoprom_尤物国产在线一区手机播放_精品国产一区二区三_色天使久久综合给合久久97