0

In C#, we have Console.WriteLine, and when programming a Linear Program, where optimization and overhead is important, I want to know, how necessary is it to use "\n" in the same Console.WriteLine instead of calling this again and again if I want to print lets say 10 lines:

Console.WriteLine("line1\n line2\n line3\n line4\n...");

as you can see this statement can be very long, and it's not a good programming habit.

alperc
  • 373
  • 2
  • 18
  • 2
    The only way to find out is to measure it. If performance is that big a concern that you consider condensing method calls, don't write to the console or maybe don't even use .NET. – CodeCaster Dec 03 '14 at 12:27
  • 1
    As a side note, you should really be using `Environment.NewLine` in lieu of `\n`, which you can do in the following way: `Console.WriteLine(String.Join(Environment.NewLine, "Line 1", "Line 2"))` – dav_i Dec 03 '14 at 12:33

2 Answers2

3

The decision to split this into one or more lines of code is negligible compared to the time it actually takes to output anything to console. If you need performance, output less.

nvoigt
  • 75,013
  • 26
  • 93
  • 142
0

If it's because of having to manage all the lines in one string, try using this method that I put together quick. It takes all the lines from a string array and formats it into what you want. Not sure how performance-wise effective it is, but it's definitely gonna help you with reading the lines better.

protected void Page_Load(object sender, EventArgs e)
{
    string[] lines = { "This is line 1", "This is line 2", "This is line 3", "This is line 4" };

    Console.WriteLine(FormatLines(lines));
}

public string FormatLines(string[] lines)
{
    string putTogetherQuery = "";

    for (int i = 0; i < lines.Length; i++)
        putTogetherQuery += "{" + i + "}\n ";

    return String.Format(putTogetherQuery, lines);
}
Kevin Jensen Petersen
  • 423
  • 2
  • 22
  • 43