Experiment
Let suppose you have million of digits that you want to print on the screen one next to each other using Java. There are two approaches that I identified :
- You can either choose to print each digit at the time (one digit next to each other) like so :
import java.util.Random;
public class Generate_Million_Digits {
public static void main(String[] args) {
Random rand = new Random();
long start = System.currentTimeMillis();
for (int i = 1; i <= 1000000; i++) {
System.out.print(rand.nextInt(10));
}
System.out.println();
long end = System.currentTimeMillis();
System.out.println("Elapsed Time in milli seconds: " + (end - start));
}
}
The elapsed Time in milli seconds is : 5248
- Or you can decide to concatenate all the digit you want to print in a special dat structure like a String or String Builder and then just print the string builder once like so :
import java.util.Random;
public class Generate_Million_Digits {
public static void main(String[] args) {
Random rand = new Random();
long start = System.currentTimeMillis();
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 1000000; i++) {
sb.append(rand.nextInt(10));
}
System.out.println(sb.toString());
long end = System.currentTimeMillis();
System.out.println("Elapsed Time in milli seconds: "+ (end - start));
}
}
The elapsed Time in milli seconds: 53
Story
The story is that I was recently solving a problem on Codeforces.com
using Java 1.8.0_241
. As part of my solution I needed to print a series of digits. My first intuition was to use the first approach I described above because it avoided me using additional data structures. It felt into the Time limit Exceeded
issue with one of the test case. So, I asked myself how to fix the TLE
. I then tried the second approach. Here, the test that was failing with TLE
passed with the second approach. Therefore, I was able to solve the problem. The good thing is that in order to solve the problem, I had to introduce a data structure (here a StringBuilder
) to avoid making many prints. There could be many more interesting technics out there.
Lesson
In Java, when you have to print many digits one next to each other, please prioritize concatenating all the digits into a data structure (StringBuilder
, it is mutable) and print the bulk once, instead of printing one digit at the time one after each other.
Based on the conversation that is currently going on this article, you can also consider using the OutputStream I/O
for the printing matter, because OutputStream
is proved to give better result in terms of time of printing. Check the comments sections to get more insights.
Happy Coding !!!