我有非常大的字符串列表和数组,我发现了两个我想解决的问题:
的所有条目
这可以是两个不同的解决方案。。不确定是否有比基本循环更快的方法,或者这样:
array = array.Where(r=>!String.IsNullOrEmpty(r.Trim());发布于 2012-02-15 17:38:27
对于一个List<T>,有一个可能更快的等价物,它执行就地删除,RemoveAll
// We can do better than this - see below...
list.RemoveAll(r => String.IsNullOrEmpty(r.Trim()));就如何执行列表中的重新定位而言,这可能会更快。
当然,这也取决于你是否想要就地搬迁。就我个人而言,我通常更喜欢LINQ方法,因为现在它更灵活、更惯用了--我通常把集合当作不可变的序列,即使它们不是真的:)
要注意的一点是:您不需要修剪字符串来确定它是否有空格。您可以使用string.IsNullOrWhiteSpace,它实际上应该被称为IsNullOrEmptyOrWhitespace --基本上“它没有内容”。
这很容易对性能产生很大的影响--如果您有大量长字符串,只需要确定其中有一些内容就没有必要使用O(N)操作(Trim) .当你又要扔掉一个新字符串的时候,创建一个新的字符串是没有意义的。
注:尺寸从早期版本改变,以便区分最后三种情况.
下面是一个例子:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
public class Test
{
static void Main()
{
List<string> list = new List<string>();
string longString = new string('x', 1000) + " ";
for (int i = 0; i < 1000000; i++)
{
list.Add(i % 100 == 0 ? "" : longString);
}
Stopwatch sw = Stopwatch.StartNew();
list.Where(r=> !string.IsNullOrEmpty(r.Trim())).ToList();
sw.Stop();
Console.WriteLine("IsNullOrEmpty(Trim): {0}", sw.ElapsedMilliseconds);
GC.Collect();
sw = Stopwatch.StartNew();
list.Where(r=> !string.IsNullOrWhiteSpace(r)).ToList();
sw.Stop();
Console.WriteLine("IsNullOrWhitespace: {0}", sw.ElapsedMilliseconds);
GC.Collect();
sw = Stopwatch.StartNew();
List<string> listResult = new List<string>();
int countList = list.Count;
for (int i = 0; i < countList; i++)
{
string item = list[i];
if (!string.IsNullOrWhiteSpace(item))
{
listResult.Add(item);
}
}
sw.Stop();
Console.WriteLine("New list: {0}", sw.ElapsedMilliseconds);
GC.Collect();
// This has to be last, as it modifies in-place
sw = Stopwatch.StartNew();
list.RemoveAll(r => string.IsNullOrWhiteSpace(r));
sw.Stop();
Console.WriteLine("List.RemoveAll: {0}", sw.ElapsedMilliseconds);
}
}在我的笔记本电脑上的样本结果:
IsNullOrEmpty(Trim): 3573
IsNullOrWhitespace: 452
New list: 232
List.RemoveAll: 153发布于 2012-02-15 17:36:12
一个经典的for/foreach总是比任何Linq更快地实现对象表达式,因为Linq在场景后面使用for/ForEach。
发布于 2012-02-15 17:36:44
脑海中唯一想到的是使用IsNullOrWhitespace方法。
array = array.Where(r=>!String.IsNullOrWhitespace(r));我怀疑你会注意到速度的差异。这是微观优化的一个极端例子。
https://stackoverflow.com/questions/9298280
复制相似问题