Programming in an efficient way
11 November 2007I 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:
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.
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 programme. This surely is useful and an easy way to debug but this also slows down the programme considerable. Don’t forget to remove this when you are code testing.
Happy coding.
Related Posts:
Top Of Page | Trackback
If you found this page useful, consider linking to it. Simply copy and paste the code below into your web site.
It will look like this: Programming in an efficient way
Don’t be too worked up about some extra String.length() calls:
public int length() {
return count;
}
Be more concerned about all of those charAt() calls:
public char charAt(int index) {
if ((index = count)) {
throw new StringIndexOutOfBoundsException(index);
}
return value[index + offset];
}
A lot of the time, it’s more efficient to to call
char[] chars = String.toCharArray()
and use chars[i] instead of a whole bunch of method calls.
//If you have JDK >= v1.5, The following code is more
//efficient, and solves other idiosyncrasies, as well,
//including possible security, multithreading, and Object
//maintenance issues. The use of “final” is an excess for
//demonstration, and does little to help nor hurt.
package demo;
public class Demo {
public static final void main(final String[] args) {
final String msg = “Efficiency demo.”;
for (char ltr : msg.toCharArray()) {
System.out.print(ltr);
}
}
}