为什么使用HTMLstring对NSAttributedString的初始调用比后续调用要长100倍?

我需要在我的iOS应用程序中显示HTML文本。 我决定我将使用NSAttributedStringinitWithData:options:documentAttributes:error:内置方法。 实际的parsing工作很好,但是,我似乎遇到了一个非常奇怪的错误,只有似乎表明自己,如果我有debugging器附加。

这种方法第一次被调用,运行iOS 7.0.4的iPhone 5S运行时间仅为1秒,iPod Touch 5代运行时间约为1.5秒。 模拟器上也出现了这个怪癖,但由于模拟器的速度很快,所以这个问题显而易见。

接下来的通话只需要10-50ms左右,比起初始通话要快得多。

这似乎与inputstring的caching没有关系,因为我在“真实”应用程序中用多个inputstringtesting了它。

但是,当我运行程序没有debugging器,它按预期运行,需要约10-20毫秒,这是我期望的HTMLparsing。

这是代码的相关部分:

 -(void) benchmarkMe:(id)sender { NSData *data = [testString dataUsingEncoding:NSUTF8StringEncoding]; NSTimeInterval startTime = [[NSDate date] timeIntervalSinceReferenceDate]; // So the complier doesn't keep complaining at me. __attribute__((unused)) NSAttributedString *parsed = [[NSAttributedString alloc] initWithData:data options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding) } documentAttributes:nil error:nil]; NSTimeInterval endTime = [[NSDate date] timeIntervalSinceReferenceDate]; NSString *message = [NSString stringWithFormat:@"Took %lf seconds.", endTime - startTime]; UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Benchmark complete!" message:message delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil]; [alertView show]; } 

注意 :一个完整​​的工作项目展示这个错误可以在这里find:
https://github.com/richardjrossiii/NSAttributedStringHTMLBug

我疯了吗? 有什么我在这里失踪? 1秒钟是我试图优化我的应用程序的性能非常大量的时间。

我目前的解决scheme是parsing应用程序启动时的“虚拟”string,但这似乎是一个令人难以置信的哈​​克解决方法。

这是一个非常好的问题。 事实certificate,(至less对我来说),无论debugging器是否连接,第一次调用方法时总是比较慢。 原因如下:第一次parsingHTML属性的string时,iOS会将整个JavaScriptCore引擎和WebKit加载到内存中。 看:

我们第一次运行该方法(parsingstring之前)只存在三个线程: 在这里输入图像说明

stringparsing后,我们有11个线程: 在这里输入图像说明

现在下一次我们运行这个方法的时候,大部分的web相关的线程仍然存在: 在这里输入图像说明

这就解释了为什么第一次和之后的速度都很慢。