Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time complexity of system.out.println

I've been told different things over my course on algorithms, and was wondering if I could get a definitive answer as to the time complexity of Java's System.out.println() command.

For example, what would the time complexity of the following be, with respect to N?

String stringy = "";
while(stringy.length() < N) {
    System.out.println(stringy);
    stringy += "X";
}

Thanks for helping out the new guy!

like image 348
Addison Avatar asked Sep 08 '13 05:09

Addison


People also ask

What is the time complexity in Java?

Usually, when we talk about time complexity, we refer to Big-O notation. Simply put, the notation describes how the time to perform the algorithm grows with the input size. Useful write-ups are available to learn more about Big-O notation theory and practical Java examples.

What is the fastest way to system out Println in Java?

Just type "sysout" in your Java editor and press Ctrl + space, which triggers code completion. This will expand sysout into System. out. println("") and place your cursor inside println() method argument to enter messages.

What is the time complexity for for loop?

The loop executes N times, so the sequence of statements also executes N times. Since we assume the statements are O(1), the total time for the for loop is N * O(1), which is O(N) overall.

What is the time complexity of two for loops?

Two nested for loops: O(n²) In the above nested loop example, outer loop is running n times and for every iteration of the outer loop, inner loop is running (n - i) times.


1 Answers

the Time complexity of this code is O(N*N) because it's a loop of N times that prints. I don't know what have you been told but the time complexity of printing it not worse then O(N) in Java.

in your code you add "X" to each line, and therefor your printing will be:

X
XX
XXX
XXXX
XXXXX
XXXXXX
.
.
.

so it's complexity is calculated as an Arithmetic progression and we get:

(1+N)*N/2=O(N^2)

to read on how the command work you can read here or here:

There is a general notion that SOPs are bad in performance. When we analyze deeply, the sequence of calls are like println -> print -> write() + newLine(). This sequence flow is an implementation of Sun/Oracle JDK. Both write() and newLine() contains a synchronized block. Synchronization has a little overhead, but more than that the cost of adding characters to the buffer and printing is high.

When we run a performance analysis, run multiple number of SOP and record the time, the execution duration increases proportionally. Performance degrades when we print more that 50 characters and print more than 50,000 lines.

It all depends on the scenario we use it. Whatever may be the case, do not use System.out.println for logging to stdout.

like image 120
No Idea For Name Avatar answered Sep 19 '22 17:09

No Idea For Name