0

I have to iterate over the elements of a string and in each iteration to perform some checks.

My question is:

What is better to use: String or StringBuilder?

Is there any difference in running time of String.charAt(i) or StringBuilder.charAt(i)?

I do NOT have to modify the string, I just have to iterate over all elements.

Dexters
  • 2,419
  • 6
  • 37
  • 57
sammy333
  • 1,384
  • 6
  • 21
  • 39

4 Answers4

0

The only reason to use a StringBuilder is for modifications (as Strings are immutable). In this case you should be fine with iterating over the String itself.

oschlueter
  • 2,596
  • 1
  • 23
  • 46
0

StringBuilder is useful when you modify a string and String when you dont.

For your case String

Regarding Performance: It will be constant time for both or negligible [1]

Note:

When you modify a string when its defined as string, it creates new string instead of actually modifying it and thats why its better to use StringBuilder

e.g)

string a = "hello";
a = "hai";

a new world string is also created here along with hello already created in string pools

Additional: http://blog.vogella.com/2009/07/19/java-string-performanc/

Community
  • 1
  • 1
Dexters
  • 2,419
  • 6
  • 37
  • 57
0

As others have already said, there is no performance difference between the two. You can convince yourself of this by looking at the source. As you can see below, the two are nigh on identical.

String.charAt()

public char More ...charAt(int index) {
    if ((index < 0) || (index >= count)) {
       throw new StringIndexOutOfBoundsException(index);
    }
    return value[index + offset];
}

StrringBuilder.charAt()

public char charAt(int index) {
    if ((index < 0) || (index >= count))
        throw new StringIndexOutOfBoundsException(index);
    return value[index];
}

In other words, use whatever you already have. If you have a String, use the String, if you have a StringBuilder, use the StringBuilder. The cost of converting from one object to the other will vastly outweigh any performance difference between these two methods.

Paul Wagland
  • 27,756
  • 10
  • 52
  • 74
0
  • String and StringBuilder both are classes in Java.
  • String is used to create a string constant.
  • StringBuilder name itself indicates to build the string. It means that we can easily do
    modification using this class.

In your case you can simply use String class.

Strings are immutable in Java. This means that after each modification a new String is created with latest modified value.

String str = new String("AVINASH");
char check = 's';
int length=str.length();
for(int i=0; i <length ; i++) {
   if (check==str.charAt(i)) {
       System.out.println("Matched");
   }
}
Richard Miskin
  • 1,260
  • 7
  • 12