How to improve NSTextStorage addAttribute performance

379 Views Asked by At

I have a long text (probably usual book like >200 pages) in NSTextStorage. I'm distributing this text for textContainers this way:

let textStorageLength = defaultTextStorage?.length ?? 0
while layoutManager!.textContainer(forGlyphAt: textStorageLength - 1, 
                                   effectiveRange: nil) == nil {
  let textContainer = NSTextContainer(size: textContainerSize)
  layoutManager!.addTextContainer(textContainer)
  pagesCount += 1
}

Then I use this containers for textViews on pageViewController.

I have some words marking like:

func selectTappableWordsFromList(_ list: [PositionWithWord]) {
  self.defaultTextStorage?.beginEditing()

  list.forEach {
    if !self.shouldInterruptCurrentProcesses {
      self.markWordInDefaultTextStorage(positionWithWord: $0)
    } else {
      self.shouldInterruptCurrentProcesses = false
      self.defaultTextStorage?.endEditing()

      return
    }
  }

  self.defaultTextStorage?.endEditing()
}


 func markWordInDefaultTextStorage(positionWithWord: PositionWithWord) {
    let range = NSMakeRange(positionWithWord.position!.start, 
                            positionWithWord.position!.length)

    defaultTextStorage?.addAttributes(defaultAttributes, range: range)
 }

 let defaultAttributes: [NSAttributedStringKey: Any] = [
    .underlineStyle: NSUnderlineStyle.styleSingle.rawValue,
    .underlineColor: UIColor.BookReader.underline
 ] 

The problem is: marking words in whole text storage is working very slow. The more pages in the book, the slower it works.

Also screenshot of cpu usage from profiler.

enter image description here

Any way to improve logic?

0

There are 0 best solutions below