存储到变量与直接传递相比(隐式创建临时变量吗?) [英] Storing to a variable vs passing directly (does that implicitly create a temp variable?)

查看:53
本文介绍了存储到变量与直接传递相比(隐式创建临时变量吗?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

模型1

NSString *name = (NSString *)[response valueForKey:@"name"];
[someObject doSomethingWith:name];

模型2

[someObject doSomethingWith:((NSString *)[response valueForKey:@"name"])];

如果我选择模型2,会保存在堆栈上创建的变量还是在幕后创建的隐式临时变量?

If i chose model 2 will that save a variable created on the stack Or still an implicit temp variable created behind he scene?

忽略可读性的损失,避免创建仅在局部使用的变量有什么好处.而不是像模型2那样直接传递它?

Ignoring loss of readability, is there any benefit in avoiding creating variable that will be used in only place. Instead passing it directly as in model 2?

推荐答案

由编译器生成的代码将相同,但是在第二种情况下没有变量.变量是高级编程概念,生成的汇编代码仅了解寄存器和内存.在这两种情况下,最内层方法调用的返回值都需要存储在某个地方,因此将使用寄存器或堆栈中的位置.

The code generated by the compiler will be the same, however, there's no variable in the second case. A variable is a high-level programming concept, the resulting assembly code knows about registers and memory only. And in both cases, the return value of the innermost method call needs to be stored somewhere, so either a register or place on the stack will be used for that.

此外,id(- [NSDictionary valueForKey:]返回的内容)是通用的,并且与任何对象指针类型隐式兼容-请不要将其返回值转换为NSString *.

Also, id (what - [NSDictionary valueForKey:] returns) is generic and implicitly compatible with any object pointer type - please, don't cast its return value to NSString *.

这篇关于存储到变量与直接传递相比(隐式创建临时变量吗?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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