Welcome to Scribd, the world's digital library. Read, publish, and share books and documents. See more
Standard view
Full view
of .
Look up keyword
Like this
0 of .
Results for:
No results containing your search query
P. 1


Ratings: (0)|Views: 63 |Likes:
Published by api-3724182

More info:

Published by: api-3724182 on Oct 18, 2008
Copyright:Attribution Non-commercial


Read on Scribd mobile: iPhone, iPad and Android.
download as PDF, TXT or read online from Scribd
See more
See less





Java performance
Reducing time and space consumption
Peter Sestoft (sestoft@dina.kvl.dk)

Royal Veterinary and Agricultural University, Copenhagen, Denmark
IT University of Copenhagen, Denmark

Version 2 of 2005-04-13
Abstract:We give some advice on improving the execution of Java programs by reducing their time
and space consumption. There are no magic tricks, just advice on common problems to avoid.
1 Reducing time consumption
1.1 Standard code optimizations

Do not expect the Java compiler (such asjavac orjikes) to perform many clever optimizations. Due to Java\u2019s rather strict sequencing and thread semantics there is little the compiler can safely do to improve a Java program, in contrast to compilers for less strictly de\ufb01ned languages such as C or Fortran. But you can improve your Java source code yourself.

\u2022Move loop-invariant computations out of loops. For example, avoid repeatedly computing the
loop bound in afor-loop, like this:
for (int i=0; i<size()*2; i++) { ... }
Instead, compute the loop bound only once and bind it to a local variable, like this:
for (int i=0, stop=size()*2; i<stop; i++) { ... }
\u2022Do not compute the same subexpression twice:
if (birds.elementAt(i).isGrower()) ...
if (birds.elementAt(i).isPullet()) ...
Instead, compute the subexpression once, bind the result to a variable, and reuse it:

Bird bird = birds.elementAt(i);
if (bird.isGrower()) ...
if (bird.isPullet()) ...

\u2022Every array access requires an index check, so it is worth-while to reduce the number of array

accesses. Moreover, usually the Java compiler cannot automatically optimize indexing into mul- tidimensional arrays. For instance, every iteration of the inner (j) loop below recomputes the indexingrowsum[i] as well as the indexingarr[i] into the \ufb01rst dimension ofarr:

double[] rowsum = new double[n];
for (int i=0; i<n; i++)
for (int j=0; j<m; j++)
rowsum[i] += arr[i][j];
Instead, compute these indexings only once for each iteration of the outer loop:
double[] rowsum = new double[n];

for (int i=0; i<n; i++) {
double[] arri = arr[i];
double sum = 0.0;
for (int j=0; j<m; j++)

sum += arri[j];
rowsum[i] = sum;
Note that the initializationarri = arr[i] does not copy rowi of the array; it simply assigns
an array reference (four bytes) toarri.
\u2022Declare constant \ufb01elds asfinal static so that the compiler can inline them and precompute
constant expressions.
\u2022Declare constant variables asfinal so that the compiler can inline them and precompute constant
\u2022Replace a longif-else-if chain by aswitch if possible; this is much faster.
\u2022If a longif-else-if chain cannot be replaced by aswitch (because it tests aString,
for instance), and if it is executed many times, it is often worthwhile to replace it by afinal
static HashMapor similar.
\u2022Nothing (except obscurity) is achieved by using \u2018clever\u2019 C idioms such as performing the entire
computation of a while-loop in the loop condition:

int year = 0;
double sum = 200.0;
double[] balance = new double[100];
while ((balance[year++] = sum *= 1.05) < 1000.0);

1.2 Fields and variables
\u2022Access to local variables and parameters in a method is much faster than access to static or instance
\ufb01elds. For a \ufb01eld accessed in a loop, it may be worthwhile to copy the \ufb01eld\u2019s value to a local
variable before the loop, and refer only to the local variable inside the loop.
\u2022There is no runtime overhead for declaring variables inside nested blocks or loops in a method.
It usually improves clarity to declare variables as locally as possible (with as small a scope as
possible), and this may even help the compiler improve your program.
1.3 Stringmanipulation
\u2022Do not build strings by repeated string concatenation. The loop below takes time quadratic in the
number of iterations and most likely causes heap fragmentation as well (see Section 2):
String s = "";
for (int i=0; i<n; i++) {
s += "#" + i;
Instead, use aStringBuilder object and itsappend method. This takes time linear in the
number of iterations, and may be several orders of magnitude faster:
StringBuilder sbuf = new StringBuilder();
for (int i=0; i<n; i++) {
}String s = sbuf.toString();
\u2022On the other hand, an expression containing a sequence of string concatenations automatically
gets compiled to useStringBuilder.append(...), so this is OK:
String s = "(" + x + ", " + y + ")";
\u2022Do not process strings by repeatedly searching or modifying aString orStringBuilder.
Repeated use of methodssubstring andindex fromString may be legitimate but should
be looked upon with suspicion.
1.4 Storing tables of constants in arrays
\u2022Declaring an initialized array variable inside a method causes a new array to be allocated at every
execution of the method:
public static int monthdays(int y, int m) {
int[] monthlengths =
{ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
return m == 2 && leapyear(y) ? 29 : monthlengths[m-1];
Instead, an initialized array variable or similar table should be declared and allocated once and for
all as afinal static \ufb01eld in the enclosing class:
private final static int[] monthlengths =
{ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
public static int monthdays(int y, int m) {
return m == 2 && leapyear(y) ? 29 : monthlengths[m-1];
\u2022More complicated initializations can use a static initializer blockstatic { ... } to precom-
pute the contents of an array like this:

Activity (5)

You've already reviewed this. Edit your review.
1 hundred reads
ZdravkoSK liked this
rahultrivedi30 liked this
iqbal_koma liked this
taha_isam liked this

You're Reading a Free Preview

/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->