用于对象的 Switch 语句的高性能 Objective C 替代方案 [英] Highly Performant Objective C Alternatives to the Switch Statement for Objects

查看:56
本文介绍了用于对象的 Switch 语句的高性能 Objective C 替代方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数,我想接收一个 NSString 和一个 int 参数,然后使用 switch 语句来返回一个计算值,就像将 int 乘以某个常数一样,这取决于所提供的 NSString.

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.

显然,switch 语句不适用于 Objective-C 中的对象.那么最快的替代方法是什么?是 if-else 语句吗?或者有没有更优雅的方法?

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?

编辑

我关心性能的原因是我正在修改用户正在观看的 UI 元素,作为这些计算的最终结果,我不希望这感觉迟钝.

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.

推荐答案

不要过早优化.只需制作一个 NSDictionary 将每个字符串映射到它的乘数.然后看看这是否足够快.

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.

这篇关于用于对象的 Switch 语句的高性能 Objective C 替代方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆