英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论