Skip to main content
Add homework tag
Link
AlexV
  • 7.3k
  • 2
  • 23
  • 47
edited tags
Link
Source Link

Optimize printing massive strings to System.out with respect to time

I need to cut the time it takes to print a large string by ~50%.

I went from using s1 + s2 to using StringBuilder, and instead of making several calls to System.out.print for each line, I create one large string by appending newlines to the StringBuilder, and then print that large string just once with System.out.

But my code is still way too slow (this is for a homework assignment and the code is not accepted by the automated hand-in system because it takes too long).

When the StringBuilder is printed, the string has ~100k lines

The relevant part of my code looks like this:

public class Main {
    public static void main (String[] args){
        MyClass builder = new MyClass();
        new ClassThatBuildsOnBuilder(builder);
        System.out.println(builder.str.toString());
    }
}
public class MyClass {
    private double[] coordinates = new double[]{0, 0, 0, 0};

    public StringBuilder str = new StringBuilder();
    private DecimalFormat formatter = new DecimalFormat("#0.0000");
    
    public MyClass(){

    }
    
    public void changeValues(double[] coordinates){
        this.coordinates = coordinates;
        updateRow();
    }

    private void updateRow(){
        for (double d : coordinates){
            str.append(formatter.format(d));
            str.append(" ");
        }
        str.append("\n");
    }

Can this even be optimized further? I feel like this should be very close to a lower bound.