Highly Performant Objective C Alternatives to the Switch Statement for Objects

眉间皱痕 提交于 2019-12-12 08:56:40

问题


I have a function which I would like to take in an NSString and an int arguments and then use the switch statement in order to return a calculated value, as in multiply the int by some constant, depending on what NSString is supplied.

Obviously, a switch statement doesn't work for objects in Objective-C. So what is the fastest alternative? Is it if-else statements? Or is there a more elegant method?

EDIT

The reason why I care about performance is that I am modifying UI elements the user is watching as the ultimate result of these calculations and I don't want that to feel sluggish.


回答1:


Don't optimize prematurely. Just make an NSDictionary that maps each string to its multiplier. Then see if that's fast enough.

If you need to do a different operation depending on the string, make each value in the dictionary a block that performs the appropriate operation.




回答2:


The reason why I care about performance is that I am modifying UI elements the user is watching as the ultimate result of these calculations and I don't want that to feel sluggish.

So... you are doing a bunch of GUI operations that involve re-layout and re-drawing of a bunch of stuff and you are worried about the performance of an if/else statement?

Graphical operations in apps are huge consumers of CPU cycles. Orders of magnitude more cycles will be consumed during drawing in response to a graphical change compared to, say, a call to objectForKey: and a call to hash (which is what a dictionary lookup implies).

Measure your app's performance. Figure out why it is sluggish. Then fix the problem.

The first step would be to use the CPU sampling Instrument to see where those cycles are going.

If that doesn't help, use one of the various graphics perf analysis tools to see if that is your bottleneck.

It can also easily be that you are doing something multiple times that needs to be done only once; maybe your user interaction tracking code is causing the UI to be re-laid out multiple times when it only needs to be done once (I just fixed exactly this kind of performance problem in an app I'm working on).



来源:https://stackoverflow.com/questions/8161319/highly-performant-objective-c-alternatives-to-the-switch-statement-for-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!