Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.

Tip of the Day
Language: Java
Expertise: Intermediate
Feb 20, 2002



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Improve the Performance of Loops

Almost all Java applications require looping at some point or other. Even the slightest improvement in looping time can make a huge performance difference. Because the size of an array doesn't change while looping, there is no need to check the length every time, for example:
for (int i=0;i<arr.length;i++).

In fact, going through the loop counting downwards instead of upwards is faster:
for (int i=arr.length-1;i>=0;i —)

In JDK 1.1 and 1.2 there is minor performance difference between counting up and counting down. But with the 1.3 release, the speed difference is greater. To test this on your system and JDK, run the program below:
public class TimeLoop {

 public TimeLoop()

int a =2;
long startTime =System.currentTimeMillis();
for (int i=0,n=Integer.MAX_VALUE;i<n;i++){
a =-a;
long midTime =System.currentTimeMillis();
for (int i=Integer.MAX_VALUE-1 ; i>=0 ; i--){
a =-a;
long endTime =System.currentTimeMillis();
System.out.println("Increasing Loop:"+(midTime -startTime));
System.out.println("Decreasing Loop:"+(endTime -midTime));


public static void main (String args []){
TimeLoop t=new TimeLoop();

Mahendra Goyal
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date