tes*_*est 4 c# linq performance
我最近发现了LINQ,我发现它非常有趣.目前我有以下功能,我不确定它是否会更高效,毕竟产生相同的输出.
你能告诉我你对此的看法吗?
该函数只是以一种非常简单的方式删除标点符号:
private static byte[] FilterText(byte[] arr)
{
List<byte> filteredBytes = new List<byte>();
int j = 0; //index for filteredArray
for (int i = 0; i < arr.Length; i++)
{
if ((arr[i] >= 65 && arr[i] <= 90) || (arr[i] >= 97 && arr[i] <= 122) || arr[i] == 10 || arr[i] == 13 || arr[i] == 32)
{
filteredBytes.Insert(j, arr[i]) ;
j++;
}
}
//return the filtered content of the buffer
return filteredBytes.ToArray();
}
Run Code Online (Sandbox Code Playgroud)
LINQ替代方案:
private static byte [] FilterText2(byte[] arr)
{
var x = from a in arr
where ((a >= 65 && a <= 90) || (a >= 97 && a <= 122) || a == 10 || a == 13 || a == 32)
select a;
return x.ToArray();
}
Run Code Online (Sandbox Code Playgroud)
Mar*_*ers 14
LINQ通常比简单循环和过程代码效率稍低,但差异通常很小,阅读的简洁性和易用性通常使得将简单投影和过滤转换为LINQ值得.
如果性能真的很重要,请测量它并自行决定LINQ代码的性能是否足够.