Let's say I wanted to print 5 lines. Which is the best method (for performance and readability).
System.out.println();
System.out.println();
System.out.println();
System.out.println();
System.out.println();
or
System.out.println("\n\n\n\n");
Is it a matter of preference or is one better than the other. It seems like it would save a lot of time using the second method.
Perhaps better than either:
That uses the line separator appropriate to your platform, where
"\n"
doesn't.There is a functional difference between the two. The first version outputs line breaks using the platform's preferred line separator. The second version outputs newline characters, which is likely to be inappropriate on Windows or Mac OS.
This is more important than any real or imagined performance advantages.
On the topic of performance, and why everyone seems to be saying "enough already".
The performance difference between your two ways of writing that code is likely to be a small number of microseconds, or less. In other words, an end user won't notice the difference ... unless the code is executed millions of times.
As a general rule, professional software engineers take the view that it is not worth spending time to make something faster if it doesn't need to be faster. And it is certainly not worth spending the client's money doing this.
You should only indulge in micro-optimization if you have clear evidence that there is, or will be a performance problem, and that the code that you are about to optimize is where the real problem is / will be. Time spent optimizing the wrong bit of code is time wasted.
So how do you know when to optimize?
And how do you know what to optimize?
Performance is not always an unimportant issue. Indeed, for some kinds of software, a design or implementation that doesn't take account of performance and scalability requirements can be a total disaster. However, most software is not like that.
The second option is almost certainly faster because each call to println() causes a system function to be called. This jump to kernel code takes some amount of time. This is the reasoning behind buffering in in C.
For platform dependent line separator I would use:
That should work on win, linux or mac.
The second option is the better method.
It is not only easier for the programmer but results in less function overhead.
As you can see from the answers, this is a matter of preference. The example you give is a very simple one where the performance gains and readability issues are minimal. In some more complicated cases, however, the choice of which seemingly equivalent methods to use could be crippling to your code, or could make it indecipherable to a neighbor.
If code looks like it's getting kind of messy, try abstracting out the messy code and giving it an easy to read method name.
So yes, this is a matter of preference.
(Edit: no, this is apparently not a matter of preference (^o^ )// )