You don't need to use StringBuilder in your example. Instead just do:
System.out.println(dfs.pop());
inside your loop. No sleeps needed either. Just one line inside the loop.
There's no problem with System.out.println() efficiency. Please consider the following code:
public class TestMain {
public static void main(String[] args) {
long timeBefore = System.currentTimeMillis();
for (int i = 0; i < 50000; i++) {
System.out.println("Value = " + i);
}
long timeAfter = System.currentTimeMillis();
System.out.println("Time elapsed (ms): " + (timeAfter - timeBefore));
}
}
This is the last lines of output on my machine:
. . .
Value = 49994
Value = 49995
Value = 49996
Value = 49997
Value = 49998
Value = 49999
Time elapsed (ms): 538
As you can see it's super fast. The problem is not in the println() method.
Example of stack usage below:
public static void main(String[] args) {
long timeBefore1 = System.currentTimeMillis();
Stack<String> s = new Stack<String>();
for (int i = 0; i < 50000; i++) {
s.push("Value = " + i);
}
long timeAfter1 = System.currentTimeMillis();
long timeBefore2 = System.currentTimeMillis();
while (!s.isEmpty()) {
System.out.println(s.pop());
}
long timeAfter2 = System.currentTimeMillis();
System.out.println("Time spent on building stack (ms): " + (timeAfter1 - timeBefore1));
System.out.println("Time spent on reading stack (ms): " + (timeAfter2 - timeBefore2));
}
Output:
. . .
Value = 2
Value = 1
Value = 0
Time spent on building stack (ms): 31
Time spent on reading stack (ms): 551