cinnamon toast
cinnamon toast

Reputation: 177

What is the run time of String.toCharArray()?

What's the run time of String.toCharArray() in java? The source code is

 public char[] toCharArray() {
    // Cannot use Arrays.copyOf because of class initialization order issues
    char result[] = new char[value.length];
    System.arraycopy(value, 0, result, 0, value.length);
    return result;
}

Does System.arrayCopy? have run time of O(n)? The source code doesn't really say much about how it's implemented. Does it go through every element and copies it? Thanks.

Upvotes: 6

Views: 3446

Answers (1)

NPE
NPE

Reputation: 500853

System.arraycopy() is typically an intrinsic and is very fast. That said, it still has to look at (and copy) every element of the array, so its asymptotic complexity is linear in the length of the array, i.e. O(n).

Thus the complexity of toCharArray() is O(n), where n is the length of the string.

Upvotes: 6

Related Questions