2

我需要将异常记录到数据库中。数据库 API 声明我可以将值作为 ByteBuffer 或 byte[] 数组传递。那么哪个更有效率呢?

private final static byte[] getThrowableStackTraceBytes(Throwable throwable) {
    StringWriter throwableStackTraceStringWriter = new StringWriter();
    throwable.printStackTrace(new PrintWriter(throwableStackTraceStringWriter));
    return throwableStackTraceStringWriter.toString().getBytes();
}

对比

private final static ByteBuffer getThrowableStackTraceByteBuffer(Throwable throwable) {
    ByteArrayOutputStream throwableStackTraceByteArrayOutputStream = new ByteArrayOutputStream();
    throwable.printStackTrace(new PrintStream(throwableStackTraceByteArrayOutputStream));
    ByteBuffer throwableByteBuffer = ByteBuffer.wrap(throwableStackTraceByteArrayOutputStream.toByteArray());
    return throwableByteBuffer;
}

我认为如果我使用 ByteBuffer,整体操作会更有效率,尤其是在它被传递到数据库方法之后进行处理时。我对吗?

(具体来说,我需要将异常记录到 Hypertable 中,它使用 Thrift Java API。)

4

1 回答 1

10

最有效的选择是两者的结合。

private final static byte[] getThrowableStackTraceBytes(Throwable throwable) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    throwable.printStackTrace(new PrintStream(baos));
    return baos.toByteArray();
}

尽管我怀疑将其写入数据库会贵很多倍。

于 2012-09-19T17:10:44.217 回答