I was browsing various blogs today and I came across a good example for using a verbatim string instead of a StringBuilder object. The code I came across looked like this (I mean absolutely no disrespect to the author, so I won't include the original link):
private void ClientScript()
{
StringBuilder sb_Script = new StringBuilder();
sb_Script.Append("<script language=\"javascript\">");
sb_Script.Append("\r");
sb_Script.Append("\r");
sb_Script.Append("function cb_verify(sender) {");
sb_Script.Append("\r");
sb_Script.Append("var val = document.getElementById(document.getElementById"
+"(sender.id).controltovalidate);");
sb_Script.Append("\r");
sb_Script.Append("var col = val.getElementsByTagName(\"*\");");
sb_Script.Append("\r");
sb_Script.Append("if ( col != null ) {");
sb_Script.Append("\r");
sb_Script.Append("for ( i = 0; i < col.length; i++ ) {");
sb_Script.Append("\r");
sb_Script.Append("if (col.item(i).tagName == \"INPUT\") {");
sb_Script.Append("\r");
sb_Script.Append("if ( col.item(i).checked ) {");
sb_Script.Append("\r");
sb_Script.Append("\r");
sb_Script.Append("return true;");
sb_Script.Append("\r");
sb_Script.Append("}");
sb_Script.Append("\r");
sb_Script.Append("}");
sb_Script.Append("\r");
sb_Script.Append("}");
sb_Script.Append("\r");
sb_Script.Append("\r");
sb_Script.Append("\r");
sb_Script.Append("return false;");
sb_Script.Append("\r");
sb_Script.Append("}");
sb_Script.Append("\r");
sb_Script.Append("}");
sb_Script.Append("\r");
sb_Script.Append("</script>");
//Inject the script into the page
Page.ClientScript.RegisterClientScriptBlock(GetType(), SCRIPTBLOCK,
sb_Script.ToString());
//Registering validator clientside javascript function
Page.ClientScript.RegisterExpandoAttribute(ClientID, "evaluationfunction",
"cb_verify");
}
There are many articles on the performance of string concatenation compared to StringBuilder, but this is an example where the verbatim string is significantly better in terms of performance and maintenance. The modified code with the verbatim string looks like this:
private void ClientScript()
{
string sb_Script = @"
<script language=""javascript"">
function cb_verify(sender) {
var val = document.getElementById(document.getElementById(sender.id).controltovalidate);
var col = val.getElementsByTagName(""*"");
if ( col != null ) {
for ( i = 0; i < col.length; i++ ) {
if (col.item(i).tagName == ""INPUT"") {
if ( col.item(i).checked ) {
return true;
}
}
}
return false;
}
}
</script>";
//Inject the script into the page
Page.ClientScript.RegisterClientScriptBlock(GetType(), SCRIPTBLOCK,
sb_Script);
//Registering validator clientside javascript function
Page.ClientScript.RegisterExpandoAttribute(ClientID, "evaluationfunction",
"cb_verify");
}
The indentation is optional if you wish to minimize the javascript, but the end result is code that is easier to maintain. (I'm still evaluating the dp.SyntaxHighlighter and I see it has an issue with the verbatim string markup.)
Technorati tags:
c#,
javascript