【发布时间】:2016-04-20 10:57:53
【问题描述】:
目前正在编写一个文件解析器,逐行遍历数据文件并清理数据。性能是此应用程序的一个重要考虑因素。用户为数据列分配标签,让进程知道哪一列代表什么类型的数据——即哪个是姓氏字段,哪个是地址字段,哪个是电话号码等等。
我刚刚写完一堆清理电话号码的代码,并像这样应用它:
public void CleanPhoneFields(FileRow row, List<Mapping> mappings)
{
// this will return empty if there's no field mapped with the "Telephone Number" tag
string phoneNumber = GetValueByAssignedLabel(row, mappings, "Telephone Number");
if(!string.IsNullOrEmpty(phoneNumber))
{
CleanTelephoneNumber(phoneNumber);
}
}
public void ProcessFile(FileContents fileContents)
{
foreach (FileRow row in fileContents.FileRows)
{
// does other cleaning functions too
CleanPhoneFields(row, fileContents.Mappings, fc);
}
}
然后我意识到,逐行检查电话字段是不必要的 - 文件中的第一行是真的,所有的都是真的。所以我最好这样做:
public void CleanPhoneFields(FileRow row, List<Mapping> mappings)
{
// this will return empty if there's no field mapped with the "Telephone Number" tag
string phoneNumber = GetValueByAssignedLabel(row, mappings, "Telephone Number");
CleanTelephoneNumber(phoneNumber);
}
public void ProcessFile(FileContents fileContents)
{
bool firstLine = true;
bool cleanPhoneNeeded = false;
foreach (FileRow row in fileContents.FileRows)
{
if(firstLine)
{
cleanPhoneNeeded = !string.IsNullOrEmpty(GetValueByAssignedLabel(row, fileContents.Mappings, "Telephone Number"));
firstLine = false;
}
if(cleanPhoneNeeded)
{
CleanPhoneFields(row, fileContents.Mappings, fc);
}
}
}
我仍然必须去获取每一行的字段值,所以在这种情况下我“保存”的只是摆脱对每一行的 string.IsNullOrEmpty 的调用。另一方面,第二个代码(在我看来)可读性稍差,并且失去了一些防御性编码。
摆脱 string.IsNullOrEmpty 会在处理周期方面为我节省很多吗?第二种方法的小缺点是否值得。还是有更好的方法来解决这个问题?
【问题讨论】:
-
你量过吗?无论如何,我希望
String.IsNullOrEmpty在微秒内执行。将两个值与零进行比较并取消引用第一个以获取第二个应该不会花费很长时间。 -
@MartinLiversage no - 那将是我的下一步。我首先询问部分是出于好奇,部分是为了确保我在这件事上没有走错路。
-
第二种效率更高。如果你可以事先确定你不需要工作,那么就去做而不做工作——这对我来说似乎非常明智。
标签: c# string performance