Multithreading – how to minimize the cost of allocating and initializing nsdateformatter?

I noticed that using nsdateformatter can be quite expensive I find that allocating and initializing objects has taken a lot of time

I created a small test application to illustrate the problem Please check it

> http://github.com/johnjohndoe/TestNSDateFormatter > git://github. com/johnjohndoe/TestNSDateFormatter. git

What are the reasons for these costs and how to improve their use?

17,12. – Update my observation: I don't understand why threads run longer than serial sequential runtime TDOA occurs only when using nsdateformatter

Solution

Note: your sample program is very small and effectively maximizes the cost of the date formatter You are doing anything, absolutely nothing So whatever happens, it seems to be slower than nothing

These tests are very valuable and misleading Micro benchmarking is usually only useful if you have a real-world teh slow If you increase this benchmark by 10 times (in fact, you may use the following suggestions), but the real world situation is only 1% of the total CPU time used by your application. The end result is no dramatic speed increase - almost inconspicuous

NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyyMMdd HH:mm:ss.SSS"];

Most likely, the cost is associated with any type of locale specific goop that parses / validates date format strings and must execute nsdateformatter Cocoa has very thorough support for localization, but the cost of this support is complex

See how to write a great example program. You can start the application in the instrument and try various CPU sampling instruments to understand what CPU cycles are consumed and how the instrument works (please update your question if you find it interesting!)

I'm surprised that when you use a single formatter with multiple threads, it doesn't simply crash Nsdateformatter does not specifically mention that it is thread safe Therefore, you must assume that it is not thread safe

Don't create so many Date formatters!

Either keep a batch of operations and delete them, or if you always use em, create an operation at the beginning of the application and keep the format changes

For threads, each thread should keep one thread if you really need it (I bet this is excessive - your application architecture is like this, and it's wiser to create one for each batch of operations)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>