[英]What is the Time Complexity of System.out.println?
Suppose code like this:假设代码如下:
String[] arr = {"Cat", "Dog", "Maple", "Blue"};
for (String str : arr) {
System.out.println(str);
}
Would the time complexity be O(N) in this case or O(N^2)?在这种情况下,时间复杂度是 O(N) 还是 O(N^2)?
At the first glance, it seems O(N) but I thought about it and since str is not constant, It's O(N^2) in this case?乍一看,似乎是 O(N) 但我仔细想想,既然 str 不是常数,那么在这种情况下是 O(N^2) 吗?
The time complexity for the for
loop will be O(n)
where n
is the size of the array. for
循环的时间复杂度为O(n)
,其中n
是数组的大小。
The System.out.println()
take O(k)
time to print k
characters the average time complexity of the above piece of code should be O(nk)
; System.out.println()
需要O(k)
时间来打印k
字符,上面这段代码的平均时间复杂度应该是O(nk)
;
The System.out.println
internally uses the following code: System.out.println
内部使用以下代码:
public void write(String str, int off, int len) throws IOException {
synchronized (lock) {
char cbuf[];
if (len <= WRITE_BUFFER_SIZE) {
if (writeBuffer == null) {
writeBuffer = new char[WRITE_BUFFER_SIZE];
}
cbuf = writeBuffer;
} else { // Don't permanently allocate very large buffers.
cbuf = new char[len];
}
str.getChars(off, (off + len), cbuf, 0);
write(cbuf, 0, len);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.