Can anyone help me how to optimize this method?
public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
{
VirtualPathData path = base.GetVirtualPath(requestContext, values);
if (path != null)
{
string virtualPath = path.VirtualPath;
string condition = string.Empty;
if (virtualPath.Contains("?"))
{
condition = virtualPath.Substring(virtualPath.IndexOf("?"));
virtualPath = virtualPath.Substring(0, virtualPath.IndexOf("?"));
}
virtualPath = virtualPath.Replace(@"%C5%BD", "ž");
virtualPath = virtualPath.Replace(@"%C4%90", "đ");
virtualPath = virtualPath.Replace(@"%C4%86", "ć");
virtualPath = virtualPath.Replace(@"%C4%8C", "č");
virtualPath = virtualPath.Replace(@"%C5%A0", "š");
virtualPath = virtualPath.ToLower().Replace(",", "-").Replace("%20", "-").Replace("&", "-");
virtualPath = virtualPath.Replace(@"-amp;", "&");
while (virtualPath.Contains("--"))
{
virtualPath = virtualPath.Replace("--", "-");
}
path.VirtualPath = virtualPath + condition;
}
return path;
}
In this code you are scanning the string three times for a character:
Instead, scan it once and use the result three times. Also scan for a char instead of a string:
Here you are doing several replaces with the same replacement:
Instead you can use a regular expression to match all of them:
(Whether this actually gives better performance has to be tested with some of your actual data. Eventhough it’s less operations, there is some overhead in setting up the regular expresson.)
You are using a loop to reduce clusters of characters:
Instead you can use a regular expression to make a single replacement: