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:
To play with the project, download the file, open up main.m.
- Change ITEMS_COUNT to the number of strings you want measured.
- 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.
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