3

I have a method that accepts a String parameter. I need to convert my String to a char[] for processing. However, if my String is greater than a certain length, I can stop processing my method logic.

public void doSomething(String str) {
  char[] strArray = str.toCharArray();
  // do something
}

I know that in terms of space efficiency, I should just check str.length() before creating my char[]. However, this got me thinking. In terms of time complexity, which is more efficient assuming I needed the char[] anyways?

Assuming I already have two objects String and char[], which is faster/more efficient?

  1. str.length()

  2. strArray.length

3
  • @yshavit You are correct. I am wrong. Commented Mar 26, 2014 at 16:56
  • @yshavit: So they stopped sharing char arrays in Java 8? Commented Mar 26, 2014 at 16:56
  • 1
    @AaronDigulla They stopped doing that half way through 7. Commented Mar 26, 2014 at 16:59

2 Answers 2

10

Since you have both objects already, the time complexity is the same: it's O(1), because both java.lang.String and Java arrays store their length for direct retrieval.

However, you can improve upon the timing of your method by using getChars method of the string to avoid copying the characters past the end of the substring that you need:

int maxLength = 100;
int effectiveLength = Math.min(maxLength, str.length());
char[] strArray = new char[effectiveLength];
str.getChars(0, effectiveLength, strArray, 0);

If it happens that your algorithm can stop processing before reaching the end of the string, this approach would let you avoid allocating the extra memory and copying the characters into it.

Sign up to request clarification or add additional context in comments.

Comments

7

That depends on how the method is implemented and the Java API gives no guarantees for that.

The current implementation is that toCharArray() will give you a copy of the String's underlying buffer, so it's a very expensive operation (memory allocation + copy many bytes), especially compared to str.length() which just returns the value of an internal final field (at least in Java 6).

In Java 7+, they seem to have stopped sharing the underlying character array (now, substr() always makes a copy).

10 Comments

The OP makes fairly clear they're already calling toCharArray(), and doing it only once; this seems irrelevant.
@LouisWasserman: Nope: "I should just check str.length() before creating my char[]."
@clcto: Your edit is wrong. String.length() does not return the length of the underlying char array.
@AaronDigulla my edit was just adding a "`" at the end of str.length()
@AaronDigulla i did. "Added one character in body." check the markdown edit history.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.