maximcore
maximcore

Reputation: 23

What is faster use StringBuilder to create string and then print result into a file or use PrintWriter to print it at once?

I need to print my List(numbers from 1 to 1000 into a file.

What is work faster: Create StringBuilder and append each number and then print this string using PrintWriter(using for-loop: for(int item: list){})

or

Use PrintWriter right away?

Or maybe there is the fastest alternative

Upvotes: 0

Views: 420

Answers (2)

Stephen C
Stephen C

Reputation: 718798

I need to print my List(numbers from 1 to 1000 into a file.

What is work faster:

Sorry, but you are asking the wrong question here.

  1. Writing the numbers 1 to 1000 to a file is probably a task that only needs to be done once. It doesn't matter it takes 1 second or 10 seconds to perform the task. 99.5% of your time is going to be taken up with writing, compiling, fixing compilation errors and debugging.

    And indeed, if you factor in the time you have taken to write this question and read the answers, it is probably closer to 99.9% of your time.

  2. The runtime of a Java application that writes 1000 numbers to a file is likely to be something like1 this:

    • 0.5 seconds starting the JVM and loading the classes that are needed and other warmup activities
    • 0.05 seconds creating / opening the file and closing it
    • 0.05 seconds formatting and writing the data

    Now suppose that there is a 20% difference between the two ways of doing this. If you do the sums, the overall execution savings from your optimization efforts will be 0.01 seconds out of 0.60 seconds.

In short, optimizing your code is simply not worth the effort.

1 - These numbers are all guesses. But I think they are ballpark correct.


However, if you really want to spend your time on this, be scientific. Write yourself a benchmark and measure which approach is faster. Read about how to do benchmarking in Java properly here:

Upvotes: 2

Philipp Claßen
Philipp Claßen

Reputation: 43979

Writing 1000 values is not a lot, so both solutions will get the job done. If you use the defaults of PrintWriter (no automatic line flushing), it should be similar in performance compared to writing to a StringBuilder first. Disk IO should be the bottleneck in both cases.

Once you have to deal with huge outputs, performance might become relevant, but both approaches are not optimal in that case. In that case, the nio package might be worth a look if IO performance is critical.

But from what you describe, I would not recommend nio, as its API is complicated. Start with a simple StringBuilder if it is convenient or use PrintWriter directly. Both should be sufficient for your use case.

Upvotes: 0

Related Questions