OPT.PCTS
Use 'charAt()' instead of 'startsWith()' for one character comparisons
Description
This rule flags code that uses `startsWith()' instead of `charAt()' for one character comparisons.
Using 'startsWith()' with a one character argument works fine, but from a performance perspective, this method is a misuse of the String API. 'startsWith()' makes quite a few computations preparing itself to compare its prefix with another string.
Example
package OPT;
public class PCTS {
private void method(String s) {
if (s.startsWith("a")) { // violation
// ...
}
}
}
Repair
Replace 'startsWith()' with 'charAt()'.
package OPT;
public class PCTS {
private void method(String s) {
if ('a' == s.charAt(0)) {
// ...
}
}
}
Reference
Bulka, D. Java Performance and Scalability Volume 1: Server-Side Programming Techniques.
|