我正在考虑是否有两个指针更好,一个用于每个对象子类和父类(super class),或者我是否应该只使用转换。
这使用了多少系统资源:
objectName.functionOne();
((SubClass) objectName).functionOther();
是否优于:
SuperClass objectA = (SuperClass) getSameInstance();
SubClass objectB = getSameInstance();
objectA.functionOne();
objectB.functionOther();
基本上,我的主要问题是关于转换使用的资源,而不是制作额外的指针。似乎我可以保存几个在线转换,例如:
((SubClass) objectName).functionOther();
但是,这值得吗?
谢谢,
格雷
更新:
我的问题有一些不清楚的部分。基本上,我有一个通过大型函数使用的父类(super class)。它适用于三个子类。一些父类(super class)正在按我的意愿工作。但是,我在几个地方遇到了障碍,我必须使用来自三个不同子类之一的函数;一个仅在其中一个子类中的函数。
我可以:
SuperClass instanceRef;
SubClass instanceRef2;
instanceRef.etc()
instanceRef.etc2()
instanceRef.etc3()
instanceRef2.specialSubClassOnlyCall();
instanceRef2.specialSubClassOnlyCall2();
或者我可以:
SuperClass instanceRef;
instanceRef.etc()
instanceRef.etc2()
instanceRef.etc3()
((SpecialSubClass)instanceRef).specialSubClassOnlyCall();
((SpecialSubClass)instanceRef).specialSubClassOnlyCall2();
但是,我不知道哪个更有效率。
更新 2:
下面是一个例子,向您展示我在说什么:
class Shape
Triangle extends Shape
Square extends Shape
Circle extends Shape
Cube extends Shape
两个指针示例:(在一个额外的指针下方。)
Shape pointer1 = (Shape) getSomeRandomShape();
Cube pointer2 = null;
pointer1.getWidth();
pointer1.getHeight();
pointer1.generalShapeProp();
pointer1.generalShapeProp2();
pointer1.generalShapeProp3();
if(sure_its_cube)
{
pointer2 = (Cube) pointer1;
pointer2.getZAxis();
pointer2.getOtherCubeOnlyThing();
pointer2.getOtherCubeOnlyThing2();
pointer2.getOtherCubeOnlyThing3();
pointer2.getOtherCubeOnlyThing4();
}
或者我可以这样做。 (下面是一堆类型转换。)
Shape pointer1 = (Shape) getSomeRandomShape();
pointer1.getWidth();
pointer1.getHeight();
pointer1.generalShapeProp();
pointer1.generalShapeProp2();
pointer1.generalShapeProp3();
if(sure_its_cube)
{
((Cube)pointer1).getZAxis();
((Cube)pointer1).getOtherCubeOnlyThing();
((Cube)pointer1).getOtherCubeOnlyThing2();
((Cube)pointer1).getOtherCubeOnlyThing3();
((Cube)pointer1).getOtherCubeOnlyThing4();
}
那么 5 次转换是否比 1 个额外的指针更糟糕?什么是 6 次,还是 20 次?一个 Actor 比指针更糟糕。
格雷
最佳答案
做任何让代码更清晰的事情,忘掉微优化。
关于java - 转换在 Java 中需要多少处理和内存使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3968913/