Gary In
Gary In

Reputation: 727

String methods - to array or not to array?

When it comes to doing computations on String, is it better to convert them to char arrays and then work on them? So all String problems are really array problems?

For instance, what would be the better method in terms of performance? What are the advantages/disadvantages?

public static String repeatEnd1(String str, int n) {
    StringBuilder sb = new StringBuilder();
    if (n <= str.length()) {
        String lastChars = str.substring(str.length() - n);
        for (int i = 0; i < n; i++) {
            sb.append(lastChars);
        }
    }
    return sb.toString();
}

public static String repeatEnd2(String str, int n) {
    if (n > str.length()) {
        return str;
    }
    char[] chars = str.toCharArray();
    char[] lastN = Arrays.copyOfRange(chars, chars.length - n, chars.length);
    char[] nLastN = new char[n * n];
    int i = 0, j = 0;
    while (i < nLastN.length) {
        if (j > n - 1) {
            j = 0;
        }
        nLastN[i++] = lastN[j++];
    }
    return String.valueOf(nLastN);
}

Upvotes: 1

Views: 75

Answers (3)

TheLostMind
TheLostMind

Reputation: 36304

subString() internally creates a new String which uses Arrays.copyOf() (which again uses System.arrayCopy() to copy the array.

That being said, JIT provides its own intrinsic implementation of arrayCopy() so your Arrays.copyOf might be replaced.

Conceptually the second option should be faster than the first one because it just deals with primitive types (Arrays can be included under this category although they aren't exactly primitives).

If you are using Synchronization, then using Strings is better because JIT removes unwanted Synchrnonization on Strings because they are immutable.

Upvotes: 1

Mehran
Mehran

Reputation: 11

I prefer to use String class. Why?

  1. it's simple and easier than char array
  2. you can easily change charset
  3. it`s cover all of my problems and more and more

Upvotes: 0

Razib
Razib

Reputation: 11163

I think the leave the String as it is - only convert to char array when it is really necessary. In you given example the first one is pretty OK. No need to convert it to char array. But some case, I know it important to use char array like - representing password. In this case you may convert them to char array.

Upvotes: 0

Related Questions