在我在Code Review.stackexchange上提出问题后,我得到了使用以下代码片段的建议。我注意到在传输过程中,字符串数组Lines被设置为IEnumerable。
在浏览IEnumerable函数一段时间后,我没有发现任何表明性能改进的东西。那么这只是为了可读性吗?或者使用IEnumerable是否真的有性能差异或一般优势,而不是使用数组?
private void ProcessSingleItem(String fileName, String oldId, String newId)
{
string[] lines = File.ReadAllLines(fileName);
File.WriteAllText(fileName, ProcessLines(lines, oldId, newId));
}
private String ProcessLines(IEnumerable<String> lines, String oldId, String newId)
{
StringBuilder sb = new StringBuilder(2048);
foreach (String line in lines)
{
sb.AppendLine(line.Replace(oldId, newId));
}
return sb.ToString();
}
IEnumerable<T>
在性能方面的实现方式。 - Daniel A. WhiteIEnumerable<T>
,那么只要它实现了IEnumerable<T>
,你就不必关心它是Array
、List<T>
还是其他任何对象。这对于想要传递Where
结果的情况非常有用。换句话说,对我来说,这更多的是关于灵活性而不是性能。 - crashmstrstring[] lines
,那么您只能传递字符串数组。 - Ben Robinson