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

2019-07-12 18:42发布

问题:

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.

回答1:

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.