Does declaring a separate variable and then referencing it cost more space than to set the reference to the new variable?

huangapple go评论74阅读模式
英文:

Does declaring a separate variable and then referencing it cost more space than to set the reference to the new variable?

问题

我找不到直接回答这个问题的内容,但如果我有误,请提供正确问题的链接。

基本上,我在问是否有任何这种做法的缺点:

MyObject myObject = new MyObject();
this.classReference = myObject;

与这种做法相比:

this.classReference = new MyObject();

我的猜测是,在代码编译为字节码后,差异将是可以忽略的。

英文:

I can't find anything that is a direct answer to this question but if I am mistaken please link the right question.

Essentially, I'm asking whether there are any disadvantages of this:

MyObject myObject = new MyObject();
this.classReference = myObject;

as compared to this:

this.classReference = new MyObject();

My guess is that differences would be negligible after the code is compiled to bytecode.

答案1

得分: 3

在这段代码中:

MyObject myObject = new MyObject();
this.classReference = myObject;

你有两个变量保存对同一个对象的引用。重要的是要理解,'myObject' 不是 '一个对象',它保存着对一个对象的引用。'new' 返回一个引用,这个引用被存储在 myObject 中,然后复制到 classReference 中。

(顺便说一下,你的变量名似乎取得不太准确 —— 它不是指向一个类的引用,而是指向一个对象的引用,一个类的实例。)

所以上述代码与这段代码之间唯一的区别是:

this.classReference = new MyObject();

在前一种情况中,为局部变量分配了堆栈空间(但分配可能在方法序言中进行,因此不会花费额外的时间),然后你需要将引用复制到其他地方。额外的开销非常非常小。

这是在假设编译器不会在第一种情况下优化掉 'myObject' 的情况下。

英文:

In this:

MyObject myObject = new MyObject();
this.classReference = myObject;

you have two variables holding a reference to one object. It is important to understand that 'myObject' is not 'an object', it holds a reference to an object. 'new' returns a reference, the reference is stored in `myObject', and copied to 'classReference'.

(By the way, your variable seems misnamed -- it is not a reference to a class, it is a reference to an object, an instance of a class.)

So the only difference between the above and this:

this.classReference = new MyObject();

is that in the former case, there was space allocated on the stack for a local variable (but the allocation was probably in the method prologue, so takes no extra time), and then you need to copy the reference somewhere else. The extra overhead is very very small.

This is assuming that the compiler doesn't optimize away 'myObject' in the first place.

huangapple
  • 本文由 发表于 2020年9月8日 05:29:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/63784475.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定