On using String Builder

  • Thread starter Thread starter Dev
  • Start date Start date
D

Dev

Can replacing this with stringbuilder advisable.
Or since iteration is less only 20 times, the time taken by using strings and string builder will be the same.

for( int i = 0; i< 20; i++ )
{

strCell2 = "<input type=hidden id='Id" + rwCnt + "' name='id" + rwCnt + "' value='" + ID + "' />"
+ "<input type=hidden id='hidId" + rwCnt + "' name='hidId" + rwCnt + "' value='" + kEntityName + "' />"
+ "<input type=hidden id='setupType" + ID + "' value=" + ID.ToString() + " />";

similar codes here..
other codes here....
}
 
There will be strings inside and its not empty..

strCell2 =
"<input type=hidden id='Id"
+ rwCnt +
"' name='id"
+ rwCnt +
"' value='"
+ ID + "' />"
+ "<input type=hidden id='hidId"
+ rwCnt
+
"' name='hidId"
+ rwCnt
+ "' value='"
+ kEntityName
+ "' />"
+ "<input type=hidden id='setupType" + ID + "' value=" + ID.ToString() + " />";
 
hi,
Can replacing this with stringbuilder advisable.
Or since iteration is less only 20 times, the time taken by using strings and string builder will be the same.

for( int i = 0; i< 20; i++ )
{

strCell2 = "<input type=hidden id='Id" + rwCnt + "' name='id" + rwCnt + "' value='" + ID + "' />"
+ "<input type=hidden id='hidId" + rwCnt + "' name='hidId" + rwCnt + "' value='" + kEntityName + "' />"
+ "<input type=hidden id='setupType" + ID + "' value=" + ID.ToString() + " />";

similar codes here..
other codes here....
}
I would consider using String.Format() in the first place:

strTemplate =
"<input type=hidden id='Id{0}' name='id{0}' value='{1}' />" +
"<input type=hidden id='hidId{0}' name='hidId{0}' value='{2}' />" +
"<input type=hidden id='setupType{1}' value={3} />";
strCell2 = String.Format(
strTemplate, rwCnt, ID, kEntityName, ID.ToString());

Using StringBulider:

StringBuilder sb = new StringBuilder();

for ()
{
sb.AppendFormat(
strTemplate, rwCnt, ID, kEntityName, ID.ToString());
}
strCell2 = sb.ToString();



mfG
--> stefan <--
 
If the loop is extending the same string each time, then StringBuilder
might help. "as is" (simply replacing strCell2) it might make the code
easier to read, but probably won't change the performance significantly.
At the moment it will be a large (but single) string.Concat call per loop.

Personally I might refactor it anyway, but for maintainability and
security (injection) reasons.

Marc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top