读书人

替String和Listlt;Tgt;各写了一个拓展方法

发布时间: 2013-08-20 17:47:51 作者: rapoo

为String和List<T>各写了一个拓展方法:FindIndexes,望大神们从性能上优化
其中字符串的那个怎么把T约束成String和char,不能约束?目测这两个方法就比较慢,求大神优化。

public static class ExtendHelper
{
/// <summary>
/// Find some indexes of subString in a long string
/// </summary>
/// <param name="_input"></paramc
/// <param name="_lookfor"></param>
/// <param name="start"></param>
/// <returns></returns>
public static int[] FindIndexes(this String _input, String _lookfor, int start = 0)
{
List<int> result = new List<int>();
int Start = start < 0 ? 0 : start;
int current = _input.IndexOf(_lookfor, Start);
while (!current.Equals(-1))
{
result.Add(current);
current = _input.IndexOf(_lookfor, current + 1);
}
return result.ToArray();
}

//public static int[] FindIndexes(this String _input, char _lookfor, int start = 0)
//{
// List<int> result = new List<int>();
// int Start = start < 0 ? 0 : start;
// int current = _input.IndexOf(_lookfor, Start);


// while (!current.Equals(-1))
// {
// result.Add(current);
// current = _input.IndexOf(_lookfor, current + 1);
// }
// return result.ToArray();
//}

/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
/// <param name="t"></param>
/// <param name="start"></param>
/// <param name="count"></param>
/// <returns></returns>
static public IEnumerable<int> FindIndexes<T>(this List<T> list, T t, int start = 0, int count = 1) where T : IComparable<T>
{
int actualNum = 0;
int Count = count > list.Count ? list.Count : count;
int Start = start < 0 ? 0 : start;

int current = list.FindIndex(Start, v => v.CompareTo(t) == 0);

while (!current.Equals(-1) && actualNum < Count)
{
if (actualNum != 0)
current = list.FindIndex(current + 1, v => v.CompareTo(t) == 0);



if (current.Equals(-1))
break;

yield return current;
actualNum++;
}
}
}


[解决办法]
static public IEnumerable<int> FindIndexes<T>(this List<T> list, T t, int start = 0, int count = 1) where T : IComparable<T>
{
return list.Select((x, i) => new { x, i }).Skip(start).Take(count).Where(x => x.x.CompareTo(t) == 0).Select(x => x.i);
}

[解决办法]
这么简单的算法性能应该不会有大的提高了,建议
1 用最基本的循环,用 ()=> 会多一层函数调用
2 整数比较就别用 Equals 了。
有个错误:第一个方法查找下一个时不该用 current+1,应该用current+_lookfor.length,并且判断 _lookfor长度不为0.

读书人网 >C#

热点推荐