I have a composite with a method that calls methods on member objects. Each method spits out a string HTML form. The form strings can get quite large. I know I'll always be dealing with only 2 member objects here. Is it fine performance-wise to simply concatenate each return value or should I be开发者_Python百科 using StringBuilder here?
public override string RenderForm()
{
return _form1.RenderForm() + _form2.RenderForm();
}
In situations where you are just putting two strings together, then the string + operator (or equivalently string.Concat(string,string)) is just fine, regardless of how long the string are.
If this is part of a large tree structure with many pieces being assembled in other objects (which is what the question seems to imply), then a better approach may be to pass a StringBuilder instance to each component.
public override void RenderForm(StringBuilder result)
{
_form1.RenderForm(result);
_form2.RenderForm(result);
}
....
public override void RenderForm(StringBuilder result)
{
result.Append("<span class='FormName'>");
result.Append(_formName);
result.Append("</span>");
}
This would require modifying all of the components in the heirarchy, but it will likely improve memory allocation.
You can use string.Concat(_form1.RenderForm(), _form2.RenderForm())
Although it is my understanding the C# compiler will convert your code into the string.Concat call anyway.
This page has a good performance analysis of the different methods.
This is probably not anymore efficient but it wasn't mentioned.
You could also use String.Format()
public override string RenderForm()
{
return String.Format("{0}{1}", _form1.RenderForm(), _form2.RenderForm());
}
精彩评论