【发布时间】:2014-09-27 10:06:17
【问题描述】:
我正在编写扫描大段文本并对其进行一些基本统计的代码,例如大小写字符的数量、标点符号等。
原来我的代码是这样的:
foreach (var character in stringToCount)
{
if (char.IsControl(character))
{
controlCount++;
}
if (char.IsDigit(character))
{
digitCount++;
}
if (char.IsLetter(character))
{
letterCount++;
} //etc.
}
然后我从那里创建了一个像这样的新对象,它只是读取局部变量并将它们传递给构造函数:
var result = new CharacterCountResult(controlCount, highSurrogatecount, lowSurrogateCount, whiteSpaceCount,
symbolCount, punctuationCount, separatorCount, letterCount, digitCount, numberCount, letterAndDigitCount,
lowercaseCount, upperCaseCount, tempDictionary);
但是,Code Review Stack Exchange 上的一位用户指出,我可以执行以下操作。太好了,我为自己节省了大量代码,这很好。
var result = new CharacterCountResult(stringToCount.Count(char.IsControl),
stringToCount.Count(char.IsHighSurrogate), stringToCount.Count(char.IsLowSurrogate),
stringToCount.Count(char.IsWhiteSpace), stringToCount.Count(char.IsSymbol),
stringToCount.Count(char.IsPunctuation), stringToCount.Count(char.IsSeparator),
stringToCount.Count(char.IsLetter), stringToCount.Count(char.IsDigit),
stringToCount.Count(char.IsNumber), stringToCount.Count(char.IsLetterOrDigit),
stringToCount.Count(char.IsLower), stringToCount.Count(char.IsUpper), tempDictionary);
但是第二种方式创建对象大约需要(在我的机器上)额外的 ~200ms。
这怎么可能?虽然它可能看起来不是很多额外的时间,但当我让它运行处理文本时它很快就会加起来。
我应该做些什么不同的事情?
【问题讨论】:
-
第一种方式迭代字符串一次,第二种方式迭代字符串13次。字符串有多大?如果它是 10K+ 个字符,则仅迭代所有字符可能需要大量时间。
-
不知道在这里使用
LINQ会不会更快?
标签: c# performance