【发布时间】:2013-12-03 14:30:27
【问题描述】:
当我在“大”(37000 行)文本文件上运行以下代码时,为什么我的系统告诉我应用程序的内存不足?
-(void) writeToFile: (NSString*)filePath withSeparator:(NSString*) fieldSep{
NSString* completeFile = [[[NSString alloc] initWithString:@""] autorelease];
for(int i=0;i<[self numberOfRows];i++){
printf("im at line number... %i of %i\n",i,[self numberOfRows]);
for(int j=0;j<[self numberOfColumns];j++){
completeFile = [completeFile stringByAppendingString:[self objectInRow:i column:j]];
if(j<[self numberOfColumns]-1){
//separator for all columns except last one
completeFile = [completeFile stringByAppendingString:fieldSep];
}
}
completeFile = [completeFile stringByAppendingString:@"\n"];
}
NSError *error = nil;
[completeFile writeToFile:filePath atomically:NO
encoding:NSStringEncodingConversionAllowLossy error:&error];
if(error){
NSLog(@"Error writing file at %@\n%@",
filePath, [error localizedFailureReason]);
}
}
出于调试原因,我添加了 printf,前 4000 行似乎立即发生,然后慢慢变慢...我的文件包含超过 37000 行类似于这些:
1893-11-6 136 194 165
【问题讨论】:
-
好吧,不是斯波尔斯基的例子;
NSString不像strcat那样工作。 :) -
@StevenFisher:这里每次附加一个字符串时都会创建一个副本,而不是在 Spolsky 的
strcat示例中线性搜索 0。但是原理是一样的——追加是O(n),所以构建字符串是O(n^2)。 -
我应该更清楚。问题并不完全相同,但肯定是相同的原理在起作用。 :)
-
感谢@RussellZahniser,我已经阅读了维基百科的文章,现在我感到很惭愧。哦,好吧,现在学习比编写大量代码更好! :)
标签: objective-c