Skip to content

This is a console application in Cocoa to show the various ways to measure the width of text and its performance.

Notifications You must be signed in to change notification settings

lordvisionz/cocoa-string-size-performance

Repository files navigation

cocoa-string-size-performance

This is a console application in Cocoa to show the various ways to measure the width of text and its performance. There are 3 ways(that I figured out) to do this:

  • [[NSString sizeWithAttributes:]](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Classes/NSString_AppKitAdditions/index.html#//apple_ref/occ/instm/NSString/sizeWithAttributes:)
  • [[NSAttributedString size]](https://developer.apple.com/library/prerelease/ios/documentation/UIKit/Reference/NSAttributedString_UIKit_Additions/index.html#//apple_ref/occ/instm/NSAttributedString/size)
  • [NSLayoutManager](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/TextLayout/Tasks/StringHeight.html#//apple_ref/doc/uid/20001809-CJBGBIBB) (get text width instead of height)

    To play with the project, download the file, open up main.m.

    1. Change ITEMS_COUNT to the number of strings you want measured.
    2. Change ITEMS_ARRAY_CHUNK_THRESHOLD to chunk up a big array into small arrays.

      Here are some performance metrics on my Macbook Pro running Yosemite 2.3GHz Intel i7 and 8GB memory.

      Count\Mechanism    sizeWithAttributes    NSAttributedString    NSLayoutManager
      1000               0.057                 0.031                 0.007
      10000              0.329                 0.325                 0.064
      100000             3.06                  3.14                  0.689
      1000000            29.5                  31.3                  7.06

      NOTE: The NSLayoutManager mechanism creates an NSTextStorage object for every string. These objects are very heavyweight and memory intensive. By just creating 1 and re-using them however causes layout to happen for every string and the measurement time goes up to 40 seconds for a million strings.

      UPDATE

      Using CoreText is the way to go. For the above table here is the performance metric with and without multithreading.
      Count\Mechanism    Core Text NO Multithreading    Core Text Multithreading
      1000               0.018                          0.02
      10000              0.023                          0.023
      100000             0.161                          0.061
      1000000            1.46                           0.447
  • About

    This is a console application in Cocoa to show the various ways to measure the width of text and its performance.

    Resources

    Stars

    Watchers

    Forks

    Releases

    No releases published

    Packages

    No packages published