[英]dottrace and optimizing method with indexof
public static string[] GetStringInBetween(string strBegin, string strEnd, string strSource, bool includeBegin, bool includeEnd)
{
string[] result = { "", "" };
int iIndexOfBegin = strSource.IndexOf(strBegin);
if (iIndexOfBegin != -1)
{
// include the Begin string if desired
if (includeBegin)
iIndexOfBegin -= strBegin.Length;
strSource = strSource.Substring(iIndexOfBegin + strBegin.Length);
int iEnd = strSource.IndexOf(strEnd);
if (iEnd != -1)
{
// include the End string if desired
if (includeEnd)
iEnd += strEnd.Length;
result[0] = strSource.Substring(0, iEnd);
// advance beyond this segment
if (iEnd + strEnd.Length < strSource.Length)
result[1] = strSource.Substring(iEnd + strEnd.Length);
}
}
return result;
}
用法:
string[] result = null;
result = HtmlHelper.GetStringInBetween(bits[0], bits[1], tagValuePair.Value, true, true);
我正在使用dottrace,这种方法占用了我33%的CPU。 我如何优化它。 因为它,我的应用程序崩溃了或者我内存不足。 这种方法是静态的吗?
dottrace在此显示30%的cpu使用率:
System.String.IndexOf(String, Int32, Int32, StringComparison)
编辑:
GetStringInBetween(string strBegin, string strEnd, string strSource, bool includeBegin, bool includeEnd)
strBegin = "<td class=\"m92_t_col2\">"
strEnd = "</td>"
strSource = "xxxxxxxx<td class=\"m92_t_col2\">Di. 31.01.12</td>xxxxxxxxxxxxxx
includeBegin = true
includeEnd = true
then i will get result
result[0] = "<td class=\"m92_t_col2\">Di. 31.01.12</td>"
希望这对这种方法有帮助。 尝试在strBegin和strEnd之间找到字符串。
仅为了继续搜索而复制部分字符串(您的第一个SubString调用)会降低性能。 相反,请保留原始输入字符串,但使用IndexOf的重载来获取起始索引,然后调整索引计算以相应地提取结果。
另外,知道这些字符串未本地化,您可以通过在IndexOf中使用序数比较器来获得一些字符串。
遵循以下原则
public static string[] GetStringInBetween(string strBegin, string strEnd, string strSource, bool includeBegin, bool includeEnd)
{
string[] result = { "", "" };
int iIndexOfBegin = strSource.IndexOf(strBegin, StringComparison.Ordinal);
if (iIndexOfBegin != -1)
{
int iEnd = strSource.IndexOf(strEnd, iIndexOfBegin, StringComparison.Ordinal);
if (iEnd != -1)
{
result[0] = strSource.Substring(
iIndexOfBegin + (includeBegin ? 0 : strBegin.Length),
iEnd + (includeEnd ? strEnd.Length : 0) - iIndexOfBegin);
// advance beyond this segment
if (iEnd + strEnd.Length < strSource.Length)
result[1] = strSource.Substring(iEnd + strEnd.Length);
}
}
return result;
}
对于您的示例输入,似乎您正在使用HTML片段。
我建议使用HTML Agility Pack解析HTML-使用LINQ to XML或XPath类型的语法,以易于查询的方式公开结果。 这是一个快速高效的库。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.