看板 java 關於我們 聯絡資訊
請問一下 假設代碼如下兩段 1. for(int i=0;i<10000;i++){ User user = new User(); ... } 2. User user = null; for(int i=0;i<10000;i++){ user = new User(); ... } 在執行上的效能會有差嗎? 先不論new Object產生的多寡 單純宣告的寫法來說,只宣告一次與宣告一萬次 是不是已第二點來說比較好呢? 謝謝 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 36.225.160.124 ※ 文章網址: https://www.ptt.cc/bbs/java/M.1478704177.A.F70.html
pttworld: 百萬級數人有感。問題是new。 11/09 23:16
d1288999: 其實沒有差,compiler會幫你優化,可看class檔 11/10 00:40
LPH66: 宣告沒差, 因為實際編譯之後變數位置都預先留好了 11/10 00:40
LPH66: 所以這兩種方式的差別就只是 user 這邊數外面看不看得到 11/10 00:40
LPH66: 這變數* 11/10 00:41
ssccg: 宣告只是編譯時留位置,在執行期有差的是 new 11/10 09:10
ssccg: 宣告區域變數在執行期只是method call時stack frame大一點 11/10 09:13
ssccg: 在同個method中放在什麼地方都一樣在method的stack frame 11/10 09:14
swpoker: 大量就有差~head會爆 11/10 09:47
swpoker: heap拉 11/10 09:47
adrianshum: 樓上:op 問是兩種方式有沒差。會爆heap的情況兩者都 11/11 10:34
adrianshum: 會。 11/11 10:34