预览加载中,请您耐心等待几秒...
1/10
2/10
3/10
4/10
5/10
6/10
7/10
8/10
9/10
10/10

亲,该文档总共11页,到这已经超出免费预览范围,如果喜欢就直接下载吧~

如果您无法下载资料,请参考说明:

1、部分资料下载需要金币,请确保您的账户上有足够的金币

2、已购买过的文档,再次下载不重复扣费

3、资料包下载后请先用软件解压,在使用对应软件打开

Javaperformance Reducingtimeandspaceconsumption PeterSestoft(sestoft@dina.kvl.dk) RoyalVeterinaryandAgriculturalUniversity,Copenhagen,Denmark and ITUniversityofCopenhagen,Denmark Version2of2005-04-13 Abstract:WegivesomeadviceonimprovingtheexecutionofJavaprogramsbyreducingtheirtime andspaceconsumption.Therearenomagictricks,justadviceoncommonproblemstoavoid. 1Reducingtimeconsumption 1.1Standardcodeoptimizations DonotexpecttheJavacompiler(suchasjavacorjikes)toperformmanycleveroptimizations. DuetoJava’sratherstrictsequencingandthreadsemanticsthereislittlethecompilercansafelydoto improveaJavaprogram,incontrasttocompilersforlessstrictlydefinedlanguagessuchasCorFortran. ButyoucanimproveyourJavasourcecodeyourself. •Moveloop-invariantcomputationsoutofloops.Forexample,avoidrepeatedlycomputingthe loopboundinafor-loop,likethis: for(inti=0;i<size()*2;i++){...} Instead,computetheloopboundonlyonceandbindittoalocalvariable,likethis: for(inti=0,stop=size()*2;i<stop;i++){...} •Donotcomputethesamesubexpressiontwice: if(birds.elementAt(i).isGrower())... if(birds.elementAt(i).isPullet())... Instead,computethesubexpressiononce,bindtheresulttoavariable,andreuseit: Birdbird=birds.elementAt(i); if(bird.isGrower())... if(bird.isPullet())... 1 •Everyarrayaccessrequiresanindexcheck,soitisworth-whiletoreducethenumberofarray accesses.Moreover,usuallytheJavacompilercannotautomaticallyoptimizeindexingintomul- tidimensionalarrays.Forinstance,everyiterationoftheinner(j)loopbelowrecomputesthe indexingrowsum[i]aswellastheindexingarr[i]intothefirstdimensionofarr: double[]rowsum=newdouble[n]; for(inti=0;i<n;i++) for(intj=0;j<m;j++) rowsum[i]+=arr[i][j]; Instead,computetheseindexingsonlyonceforeachiterationoftheouterloop: double[]rowsum=newdouble[n]; for(inti=0;i<n;i++){ double[]arri=arr[i]; doublesum=0.0; for(intj=0;j<m;j++) sum+=arri[j]; rowsum[i]=sum; } Notethattheinitializationarri=arr[i]doesnotcopyrowiofthearray;itsimplyassigns anarrayreference(fourbytes)toarri. •Declareconstantfi