我有一个包含超过 80,000 行和 100 列的 CSV 文件。我正在尝试以最高效的方式处理加载/访问 CSV 数据。现在我的 CSVParser 将数据加载到 NSArray 中,但它非常慢/迟钝;这是一个问题,因为我希望在移动设备上处理此解析/加载:iPhone。
如有任何关于替代方法的建议,我们将不胜感激。谢谢
更新:
为了将来的引用/讨论,我现在有以下尝试:
// Mark time the parser starts
NSTimeInterval start = [NSDate timeIntervalSinceReferenceDate];
// Parse the CSV file
[parser parse];
NSTimeInterval end = [NSDate timeIntervalSinceReferenceDate];
// Print how long the parsing took
NSLog(@"raw difference: %f", (end-start));
// Copy the allLines array from the parsing delegate
NSArray *allOfTheRows = [NSArray arrayWithArray:d.allLines];
NSLog( @"There are %i lines in the csv file", [allOfTheRows count]);
NSFileManager *f = [[NSFileManager alloc] init];
NSString *filePath = @"/Users/..../rawData"; // This is of course not a literal location...
// Archive the array as NSData
NSData *someData = [NSKeyedArchiver archivedDataWithRootObject:allOfTheRows];
// Write the data to a file
[f createFileAtPath:filePath contents:someData attributes:nil];
/*
If I were to load the data from the iPhone, i'd copy the newly created someData file above to my application's mainBundle, and then unarchive the NSData to an array on the iPhone
*/
// Read the data back as an array
NSData *readData = [NSData dataWithContentsOfFile:filePath];
NSArray *bigCollectionReadBack = [NSKeyedUnarchiver unarchiveObjectWithData:readData];
最佳答案
我在 iPhone 上解析 CSV 时遇到了类似的问题。我最终在 Mac 上进行了解析,并写出了一个包含结构数据数组的二进制文件。过去在 iPhone 4 上解析/加载 CSV 文件需要 120 秒,但二进制文件加载时间不到 10 毫秒。
编辑 - 更详细一点,在 Mac I read the CSV file ,将数据组织成几个结构数组,然后使用 fwrite 将数据写出到二进制文件中.在 iOS 上,我使用 fread 读取二进制文件(一次读取 header 以获取大小信息,第二次读取数据) 到大小合适的结构数组中。其中一个较大的文件是 2.2MB,使用 fread 从闪存读取到 RAM 需要 66 毫秒。
2011-11-15 17:32:35.304 -[BinFile initWithFile:] 001953f0 file Metro
2011-11-15 17:32:35.370 -[BinFile initWithFile:] read 2217385 bytes (Metro)
关于iphone - 加载大 CSV 文件时的性能问题 (Objective-C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8085757/