One digit or a bulk of digits — Which one to print in Java?

Revision en2, by mason_24, 2022-03-15 00:18:16

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, but I failed into the Time limit Exceeded issue with one of the test case. So I ask myself how to fix the TLE. I then tried the second approach. After trying the second approach, 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.

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.

Tags java, print, stringbuilder, time complexity, space complexity, time-space tradeoff

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en3 English mason_24 2022-03-16 03:00:33 409
en2 English mason_24 2022-03-15 00:18:16 134
en1 English mason_24 2022-03-15 00:17:26 2677 Initial revision (published)