Jtest logo




Contents  Previous  Next  Index

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.


Contents  Previous  Next  Index

ParaSoft logo
(888) 305-0041 info@parasoft.com Copyright © 1996-2001 ParaSoft