在《effectivejava》中‘避免创建不必要的对象’一节,有如下代码privatestaticlongsum(){Longsum=0L;for(longi=0;i<=Integer.MAX_VALUE;i++)sum+=i;returnsum;}Thisprogramgetstherightanswer,butitismuchslowerthanitshouldbe,duetoaone-charactertypographicalerror.ThevariablesumisdeclaredasaLonginsteadofalong,whichmeansthattheprogramconstructsabout231unnecessaryLonginstances(roughlyoneforeachtimethelongiisaddedtotheLongsum).为什么把sum设置成Long对象,会在每一次循环的时候创建Long实例?
慕的地8271018
弑天下
相关分类