November 11, 2007

JAVA Tip

In order to program in a efficient way I want to share a little tip. Even simple lines of code can create performance bottleneck. Consider the following example:
String str="If you are interested let me know";
for (int i=0;i<str.length();i++)
{
System.out.println(str.charAt(i));
}


This example prints each character of the string. In this case as the string length is 32 and loop will check string length 32 times. That's not a good programming practice.

Better way is to store the length of the string in a variable and use that in loop.

String str="If you are interested let me know";
int size = str.length();

for (int i=0;i<size();i++)
{
System.out.println(str.charAt(i));
}

This approach works in a same way but with better efficiency.




1 comment:

  1. You made size method inside the for loop.Is it okay?

    ReplyDelete