2 回答

TA貢獻2041條經(jīng)驗 獲得超4個贊
您面臨的問題不是調(diào)用,Integer.valueOf(666).toString()因為它只執(zhí)行一次。實際的問題是,調(diào)用System.out.write()有一些開銷。這可以通過使用填充了一些重復(fù)輸入值的更大緩沖區(qū)來避免。
這是我想出的:
long start = System.currentTimeMillis();
byte[] bytes = String.valueOf(666).getBytes();
// use 20 mb of memory for the output buffer
int size = 20 * 1000 * 1000 / bytes.length;
byte[] outBuffer = new byte[size * bytes.length];
// fill the buffer which is used for System.out.write()
for (int i = 0; i < size; i++) {
System.arraycopy(bytes, 0, outBuffer, i * bytes.length, bytes.length);
}
// perform the actual writing with the larger buffer
int times = 10_000_000 / size;
for (int i = 0; i < times; i++) {
System.out.write(outBuffer, 0, outBuffer.length);
}
long end = System.currentTimeMillis();
System.out.println();
System.out.println("Took " + (end - start) + "Millis");
輸出 666 千萬次大約需要 600ms。

TA貢獻1812條經(jīng)驗 獲得超5個贊
這看起來是正確的。如果您將int
666 轉(zhuǎn)換為 a char
,則將顯示該內(nèi)容。如果您想從字面上打印出 666,則需要將其轉(zhuǎn)換int
為String
第一個:
byte[] bytes = Integer.toString(input).getBytes();
添加回答
舉報