第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 System.out.write 方法將 int 轉(zhuǎn)換為字節(jié)數(shù)組并打印到控制臺

使用 System.out.write 方法將 int 轉(zhuǎn)換為字節(jié)數(shù)組并打印到控制臺

胡子哥哥 2022-05-20 18:32:01
我有這個程序:public class Duplicates {    public static void main(String[] args) {        byte[] bytes = "hz".getBytes();        for (int i = 0; i < 10_000_000; i++) {            System.out.write(bytes, 0, bytes.length);        }    }}開始后我有輸出:hzhzhzhzhzhzhzhz .....hz但是如果我嘗試轉(zhuǎn)換int 為字節(jié)數(shù)組并打?。簆ublic class Duplicates {    public static void main(String[] args) {        byte[] bytes = ByteBuffer.allocate(4).putInt(666).array();        for (int i = 0; i < 10_000_000; i++) {            System.out.write(bytes, 0, bytes.length);        }    }}開始后我有輸出:? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?入我想666在控制臺的每一行打印 10,000,000 次,并且使用的內(nèi)存不超過 20MB 或 1 秒。我究竟做錯了什么?編輯如果我將使用示例@Justin -Integer.toString(i).getBytes()我有這個:
查看完整描述

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。


查看完整回答
反對 回復(fù) 2022-05-20
?
ABOUTYOU

TA貢獻1812條經(jīng)驗 獲得超5個贊

這看起來是正確的。如果您將int666 轉(zhuǎn)換為 a char,則將顯示該內(nèi)容。如果您想從字面上打印出 666,則需要將其轉(zhuǎn)換intString第一個:

byte[] bytes = Integer.toString(input).getBytes();


查看完整回答
反對 回復(fù) 2022-05-20
  • 2 回答
  • 0 關(guān)注
  • 196 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號