Re: [問題] parse 數字

看板java作者 (勁過呂布)時間18年前 (2007/07/03 15:24), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串7/7 (看更多)
※ 引述《archerlin ()》之銘言: : 哈,你少了一個轉成int的步驟啦~ : 這樣只是印出來看起來對但還是存在String[]裡阿 : 並不能變成一個整數來做之後程式需要的運算...... : 要是我我也是只會立即想到這行最簡單的作法啦 (像PsMonkey版主的想法) : int i = Integer.parseInt("123,456,789".replace(",", "")); : 那篇被M的我測過效率還是沒有上面這行快, : 但是有時候練習程式也不是光看速度、效率這些東西的... 其實如果論速度,每次只 parse 一次 DecimalFormat 的確是比不上 replaceAll 再 Integer.parseInt 的。 (注意: 是用 replaceAll, 因 replace 是 replace character only... 我使用 JDK1.5 中) 不過當會重覆使用很多次的話,用一個 static 的 DecimalFormat Object 會比重 覆的 call replaceAll 來得快。 而如果假設輸入的 string 只能是正數,且不理會 , 的出現格式,還是使用化石級 的 primitive 處理法最快... 以下補上吃飽沒事做的程式碼 XD public static void main(String argv[]) throws Exception { int noftime = 100000; String strTMP = "13,424,555"; String pattern = "#,###;(#,###)"; Number parsedNum = null; int num = 0; long t = System.currentTimeMillis(); java.text.DecimalFormat dfmt = new java.text.DecimalFormat(pattern); for (int i=0; i<noftime; i++) parsedNum = dfmt.parse(strTMP); System.out.println("D. Format: " + (System.currentTimeMillis() - t) + "ms"); t = System.currentTimeMillis(); for (int i=0; i<noftime; i++) num = Integer.parseInt(strTMP.replaceAll(",","")); System.out.println("parseInt: " + (System.currentTimeMillis() - t) + "ms"); int result = 0; t = System.currentTimeMillis(); for (int i=0; i<noftime; i++) { result = 0; for (int j=0; j<strTMP.length(); j++) { char c = strTMP.charAt(j); if (c == ',') continue; if ( c < '0' || c > '9' ) throw new IllegalArgumentException("Unexpected character: " + c); result *= 10; result += (int) c - '0'; } } System.out.println("Primitive" + (System.currentTimeMillis() - t) + "ms"); } 得出結果是: D.Format: 297ms parseInt: 640ms Primitive: 16ms 還是 primitive 王道 XD 不過值得商榷,有多少個程式需要這樣十萬次呢?我不斷將 noftime 調低,看看到 了多少次,才會令 D.Format 和 parseInt 平手 (好啦,我們就別理 Primitive 這蠻牛了 XD) 一下子將 noftime 降到 25000: D.Format: 156ms parseInt: 219ms Primitive: 0ms 看到兩方都已經非常地接近了 (啊不是說好不提 Primitive 嗎) 繼續實驗的結果是,當 noftime 介乎 1500 - 2000 的時候,兩者的耗用時間就差不 多了,而當 noftime 比 1000 為低時,parseInt 就肯定會比 D.Format 有效率... 如果沒有 Primitive 比來攪局的話 XDrz 不過仍然強調,在實驗中只有 new 過一次 DecimalFormat。如果程式不容許有一個共 用的 DecimalFormat instance,那就沒話說了 :D -- 很多人以為 所以我要 其實我是個快 我是大學生 告訴大家 三十歲的怪叔叔 ● ●/ ︿ ︿ /\ < ● ㄨ /\ ㄨ -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 203.218.142.161 ※ 編輯: superlubu 來自: 203.218.142.161 (07/03 15:25)
文章代碼(AID): #16YVciOh (java)
文章代碼(AID): #16YVciOh (java)