我正在看一些lwjgl的教程,我突然想到,与其在变量中实例化类,不如实例化它并直接调用方法,而不保存对象。
我想知道在以后不必重用对象时这样做是否好,或者是否最好始终保留对象。
我的意思是:
(new Lesson02()).run(fullscreen);
相反,它:
Lesson02 l2 = new Lesson02();
l2.run(fullscreen);
谢谢
我正在看一些lwjgl的教程,我突然想到,与其在变量中实例化类,不如实例化它并直接调用方法,而不保存对象。
我想知道在以后不必重用对象时这样做是否好,或者是否最好始终保留对象。
我的意思是:
(new Lesson02()).run(fullscreen);
相反,它:
Lesson02 l2 = new Lesson02();
l2.run(fullscreen);
谢谢
如果以后不打算使用该对象,实际上没有任何区别。所以选项1是好的。如果您遵循选项2,并且在代码的后面没有使用<code>l2</code>,那么它无论如何都会被垃圾收集。
只要以后不必使用该对象,那么第一个选项就可以了。
我通常使用第一个选项,除非构造函数和函数有很多参数,否则为了可读性,我更喜欢将其拆分。一般规则:使用更易于理解和阅读的内容。
由于Java是一种垃圾收集语言,因此第一种方法是完全可以接受的。与第二个相比,我更喜欢它的紧凑性和无杂乱性。
这两个选项实际上是相同的。
如果编译器不善于优化,那么第一个编译器可能会更快,因为GC更有可能快速回收它。
前一个选项无论如何都会创建一个临时引用变量;无论是命名的还是未命名的,都有一个引用堆上对象的局部变量。如果它再也不用了,垃圾收集器会帮你清理的。
这两个选项仅在可读性方面不同,因此您可以从这个角度选择您喜欢的选项。
第一种方法是最好接受的,因为Java可以为您分配内存。
Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...
Check this, List<String> list = new ArrayList<String>(); for (int i = 0; i < 10000; i++) { String value = (""+UUID.randomUUID().getLeastSignificantBits()).substring(3, ...
I am in the middle of solving a problem where I think it s best suited for a decorator and a state pattern. The high level setting is something like a sandwich maker and dispenser, where I have a set ...
I have been trying to execute a MS SQL Server stored procedure via JDBC today and have been unsuccessful thus far. The stored procedure has 1 input and 1 output parameter. With every combination I ...
I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...
If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...
I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....
I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...