2011-11-10 56 views
3

我有一個包含80,000多行和100列的CSV文件。我試圖以儘可能高性能的方式處理加載/訪問CSV數據。現在我的CSVParser將數據加載到一個NSArray中,但它非常緩慢/緩慢;這是一個問題,因爲我希望在移動設備上處理這種解析/加載:iPhone。加載大CSV文件時的性能問題(Objective-C)

任何建議替代方法將不勝感激。謝謝

UPDATE:

以供將來參考/討論,我現在有以下嘗試:

// 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]; 
+0

我認爲這實際上取決於您如何使用數據以及數據是否能夠提供良好的替代方法。一個CSV聽起來可能不是最好的選擇(如果你有選擇) – Danny

回答

4

我在iPhone上有類似的CSV解析問題。我最終在Mac上進行了解析並寫出了一個包含結構數據數組的二進制文件。它過去需要120秒才能解析/加載iPhone 4上的CSV文件,但二進制文件的加載時間不到10毫秒。

編輯 - 更詳細地說明了一下,在Mac我read the CSV file,數據組織成結構的多個陣列然後將數據寫出來的使用fwrite二進制文件。在iOS上,我使用fread(其中一個讀取標題獲取大小信息,另一個讀取數據)讀取二進制文件並將其轉換爲正確大小的結構數組。其中一個較大的文件是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) 
+0

感謝您的回覆。我用一些代碼更新了我的問題。現在我將數組歸檔/解除歸檔爲NSData(仍然需要一點時間) – Alec

+0

您能否詳細說明一下?也許你使用的線沿線的東西: 的NSData * binaryPlistData = [NSPropertyListSerialization dataFromPropertyList:plist中\t \t \t \t \t \t \t \t格式:NSPropertyListBinaryFormat_v1_0 ERRORDESCRIPTION:錯誤] 謝謝 – Alec

+0

我在上面的答案中添加了更多細節。 – progrmr

1

我不知道你所說的「替代法」的意思,但如果你有一個巨大的數據集另一種方法不會幫助你。什麼可以幫助您的優化您的當前負載過程

你可以做到以下幾點:在塊

  1. 加載該文件,因此你不吹你的RAM(提示:NSFileHandle)
  2. 處理解析上與GCD多線程(使用全部處理器核心)
  3. 避免自動釋放的對象,如果您有任何確保您使用的ARP

UPDATE:

您沒有說文件保留在設備的資源文件夾中,並且不能更改(如從外部源下載)。如果是這種情況,請使用progrmr的解決方案。