Is it more efficient to convert an exception's stack trace into byte[] array or ByteBuffer (Java)?

arrays, bytebuffer, java, printstacktrace, stack-trace

Solution

The most efficient option is like to be a combination of the two.

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

though I suspect writing it to the database will be many times more expensive.

Problem

I need to log the exception into the database. The database API states I can either pass the value as ByteBuffer or as byte[] array. So which is more efficient? ``` private final static byte[] getThrowableStackTraceBytes(Throwable throwable) { StringWriter throwableStackTraceStringWriter = new StringWriter(); throwable.printStackTrace(new PrintWriter(throwableStackTraceStringWriter)); return throwableStackTraceStringWriter.toString().getBytes(); } ``` vs. ``` private final static ByteBuffer getThrowableStackTraceByteBuffer(Throwable throwable) { ByteArrayOutputStream throwableStackTraceByteArrayOutputStream = new ByteArrayOutputStream(); throwable.printStackTrace(new PrintStream(throwableStackTraceByteArrayOutputStream)); ByteBuffer throwableByteBuffer = ByteBuffer.wrap(throwableStackTraceByteArrayOutputStream.toByteArray()); return throwableByteBuffer; } ``` I think the overall operation will be more efficient if I were to use ByteBuffer, especially when it is handled after it is being passed into the database method. Am I right? (Specifically, I need to log the exception into Hypertable, and it uses the Thrift Java API.)

Original source