Re: C# Multi-line String Literals

  • From: "black ares" <matematicianu2003@xxxxxxxxxxx>
  • To: <programmingblind@xxxxxxxxxxxxx>
  • Date: Wed, 11 Aug 2010 17:31:03 +0300

if you know the entire string, specify it as a whole. This way you will skip 
concatenation and method calling.
If the string is not know, but it is formed from a small number of pieces, 
small means realy small, let say less than 10
you can use the concatenation operator namely +.
If you have a lot of pieces to concatenate, than choose the stringbuilder 
method which is more efective than the other.

For understand this you must understand how all this things work.
The class string in dotnet and in other technologies is a so called imutable 
class.
So when an object is created it remains how it is from the start to the end.
Every operation on that object returns in fact a newly created object of that 
type.
When you say:]
string s="lala";
you are creating an object and all is perfect, in therms of performance.
When the concatenation operator is involved... For concatenate, let say more 
strings than 10,
the following happens:
first two strings are concate nated, the result is stored in another part of 
memory, then this string is concatenated with the third string from the line 
and the new result is stored else where in memory.
In this way you are gething at a given time more copies of that strings in 
memory.
ccounting only the memory space, this is a non efective method.

  ----- Original Message ----- 
  From: Kerneels Roos 
  To: programmingblind 
  Sent: Wednesday, August 11, 2010 10:57 AM
  Subject: C# Multi-line String Literals


  Hi List,

  Three ways to do this, which one is best:

  1.
  StringBuilder sb = new StringBuilder();
  sb.AppendLine("SELECT id ");
  sb.AppendLine("FROM my_table ");
  sb.AppendLine("WHERE id > 5");

  2.
  string myMultiLine = "SELECT id "
     + "FROM my_table"
     + "WHERE id >5";

  3.
  string myMultiLine = @"SELECT id
     FROM my_table
     WHERE id > 5";

  Method 1 is the usual way, 2 introduces extra whitespace and lime breaks, and 
3 apparently does not result in slower code if the whole string is known at 
compile time -- the compiler is smart enough to make it into one string (see: 
http://jameskovacs.com/2007/02/12/multiline-strings-in-c/ ).

  If you know that you are going to have to tweak the string and have a few 
round trips to the query analyzer I would say that 2 would actually be best 
since you only have to remove the first @" and last "; and the literal string 
will run. Once you know the string is perfect I would say method 3 is the best 
since it looks like it might be faster than method 1 and does not have the 
extra, maybe unwanted additional whitespace and new line chars that method 2 
introduces.

  What do you guys think?

  Regards,

  -- 
  Kerneels Roos
  Cell/SMS: +27 (0)82 309 1998
  Skype: cornelis.roos

  The early bird may get the worm, but the second mouse gets the cheese!


Other related posts: