◆メインコード
package main;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
public class Main {
  public static void main(String[] args) {
    try {
      int tmp = 0 / 0;
    } catch (Exception e) {
      String s = e.getMessage();    // ★★★この行を変更する。
      System.err.println(s);
    }
  }
  public static String exToStr(Exception arg) {  // 後述する。
    try (StringWriter sw = new StringWriter()) {
      arg.printStackTrace(new PrintWriter(sw));
      return sw.toString();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return "";
  }
}
◆結果
| No | コード | 結果 | 時間※ | 
| 1 | e.getMessage() | / by zero | 1ms | 
| 2 | e.getLocalizedMessage() (例外クラスによって文字列が変わる。)  | 
  / by zero | 2ms | 
| 3 | e.toString() | java.lang.ArithmeticException: / by zero | 231ms | 
| 4 | StringWriterによる変換 (上記のメインコードのexToStr()を参照のこと。)  | 
  java.lang.ArithmeticException: / by zero at main.Main.main(Main.java:12)  | 
  1973ms | 
| 5 | ExceptionUtils.getStackTrace(e) (apache commons Lang)  | 
  java.lang.ArithmeticException: / by zero at main.Main.main(Main.java:12)  | 
  1930ms | 
| 6 | e.getStackTrace().toString() | [Ljava.lang.StackTraceElement;@1db9742 | 491ms | 
String s = "";
long start = System.nanoTime();
for (int i = 0; i < 1000 * 1000 * 1; i++)
  s = ExceptionUtils.getStackTrace(e);    // ★★★この行を変更する。
long end = System.nanoTime();
System.out.println((end - start) / 1000000  + "ms");
■VMware WorkStation10上の仮想マシン
・CPU:2
・メモリ:2GB
・OS:Windows7
・Java ver:eclipse同梱のJava8
・IDE:eclipse(pleiades) Version: Neon.1 Release (4.6.1)
■ホストPCの性能(参考)
・CPU:Intel Core i5-4250U
・メモリ:8GB
・ドライブ:SSD(Plextor PX-512M3P)
・OS:Windows10
0 件のコメント:
コメントを投稿