View RSS Feed

My Java Tips

Programming in an efficient way

Rate this Entry
by , 11-09-2011 at 06:12 PM (707 Views)
I have seen even matured programmers making few mistakes while programming, which might have performance bottleneck. I would like to mention few of such mistakes here.


A function call takes some resources. Even it seems a simple line of code, Java Runtime has to take case of few things to manage it. Consider following example:

Java Code:
String str = "Lets play football. If you are interested, let me know.";
for (int i=0; i < str.length();i++)
{
System.out.print(str.charAt(i));
}
The above example, simply prints the string character by character.

The string str has 55 characters in it, so for loop will execute 55 times. 55 times length() function will be called, which is not a good coding practice. Just assume, what if this loop had to fun thousands of times? Surely it should be avoided.

Better way is to store the length of string in an integer and use that in the loop condition.

Java Code:
String str = "Lets play football. If you are interested, let me know.";
int size = str.length();
for (int i=0; i < size;i++)
{
System.out.print(str.charAt(i));
}
The code above does the same job, but more efficiently.

One should keep a close eye on such issues because these issues are easily overlooked but these tend to slow the programs.

Also most of the programmers use System.out.print(); statement to print useful messages and values of variables to track the program. This surely is useful and an easy way to debug but this also slows down the program considerable. Donít forget to remove this when you are code testing.

Happy coding.

Submit "Programming in an efficient way" to Facebook Submit "Programming in an efficient way" to Digg Submit "Programming in an efficient way" to del.icio.us Submit "Programming in an efficient way" to StumbleUpon Submit "Programming in an efficient way" to Google

Categories
Java SE

Comments