我有这样一个类:
class Test
{
public static test getInstance()
{
return new test()
}
public void firstMethod()
{
//do something
}
public void secondMethod()
{
//do something
}
public void thirdMethod()
{
//do something
}
}
在另一个类中,如果我们用不同的方法多次调用 Test.getInstance().methodName()
,会发生什么?
在以下代码中,哪一个会更快并且使用低内存?
Test.getInstance().firstMethod()
Test.getInstance().secondMethod()
Test.getInstance().thirdMethod()
或
Test test = Test.getInstance();
test.firstMethod();
test.secondMethod();
test.thirdMethod();
最佳答案
Test.getInstance().firstMethod()
Test.getInstance().secondMethod()
Test.getInstance().thirdMethod()
这将创建三个 Test
类的不同实例,并在每个实例上调用一个方法。
Test test = Test.getInstance();
test.firstMethod();
test.secondMethod();
test.thirdMethod();
将只创建一个实例并在该实例上调用三个方法。
所以这是一种完全不同的行为。显然,既然第一个创建了三个对象,那么它应该占用更多的堆空间。
但是,如果您打算实现单例类,则两者是等效的。
关于Java : performance of the instance without variable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27027330/