Saturday, March 31, 2012

string vs stringbuilder

What can I better use?

StringBuilder sb =newStringBuilder();

sb.Append("SELECT ");

sb.Append("count(*) ");

sb.Append("FROM ");

sb.Append("table");

Or

query ="SELECT count(*) FROM table";

Look String is immutual object . you can't perform modification operation but in Stringbuilder is New type of Collection Class that provide feasibility to modify and other string operation without losing value


Hi

Strings of type System.String are immutable in .Net. That means any change to a string cause the runtime to create new string and abandon old one.

That happens invisibly, and many programmers might be surprised that following code allocate four new string in memory:

string s;

s = "select "; // "select"

s += " * from "; // "select * from"

s += " tablename"; // "select * from tablename"

Only the last string has a reference, the other two will be disposed of during garbage collection. Avoiding these types of temporary string helps avoid unnecessary garbage collection, which improve performance.

Use StringBuilder class to create dynamic (mutable) strings.

StringBuilder can span multiple statements. The default constructor creates a buffer of 16 bytes long, which grows as needed. You can specify an initial size and a maximum size if you like.

As in your case, if you do not need to break statement in query thanstringworks. Use StringBuilder when you want to span your query in multiple statement.

Hope this helps you.

Regards,

Mustakim Mansuri



If thats the case it better to use String because you did your query is simple BUT if you are trying to DO Insert with multiple values then you can use the StringBuilder to append values...

Just a little Gee-Whiz info as to how much better StringBuilder can be when you are making several concatenations (especially in a loop):

I was building an HTML string in a while(datareader.Read()) loop, and setting a divs InnerHtml equal to that string at the end. I didn't know any better, I never heard of StringBuilder. Then I came across an article about it, so I figured I'd give it a try. In one of my examples, I had about 1000 rows being returned and was making maybe 2 string concatenations within each iteration of the loop. Needless to say, it was running a little slow (between 3-5 seconds each time the user tried to access the page). After replacing straight string concatenations with StringBuilder.Append() statements, the page loaded almost immediately. A few seconds saved was pretty nice, but what further drove the importance home for me was when I remembered that the database connection was open that whole time. Multiply that by several users hitting the site at the same time, and it became very clear.

0 comments:

Post a Comment