Android 中的不可变对象有多昂贵?
How expensive are immutable objects in Android?
假设我想创建一个 class 来表示复数。对象只包含两个float,但是当然有大量的方法。
class Complex extends Number implements Comparable {
float mReal, mImaginary;
public Complex(float r, float i) {
mReal = r;
mImaginary = i;
}
/**
* Set the value of this
*/
public void set(float r, float i) {
mReal = r;
mImaginary = i;
}
/**
* Add other to this
*/
public void add(Complex other) {
mReal += other.mReal;
mImaginary += other.mImaginary;
}
// And so on and so forth
}
我知道我可以通过使它不可变来让生活变得更简单,但这意味着更多的对象创建和垃圾收集。有人知道在 Android 中这种创建和销毁的成本有多高吗? (不仅是最新版本;我还想支持设备 运行 2.x。)
我的建议是不要担心这个并继续使用不可变对象创建应用程序。
whether you should worry about this is completely dependent on where and when you create these objects
我的评论更旨在询问您是否想在应用程序的关键点(例如在绘制过程中)进行昂贵的操作。听起来好像你不是。
有趣的是,根据我的经验,使用不可变对象模式并未对我开发的应用程序的内存或性能产生明显影响。也就是说,虽然可能会产生影响,但这从来都不是明显放缓的原因。
(无可否认,我的专业经验跨越 API 14+。)
假设我想创建一个 class 来表示复数。对象只包含两个float,但是当然有大量的方法。
class Complex extends Number implements Comparable {
float mReal, mImaginary;
public Complex(float r, float i) {
mReal = r;
mImaginary = i;
}
/**
* Set the value of this
*/
public void set(float r, float i) {
mReal = r;
mImaginary = i;
}
/**
* Add other to this
*/
public void add(Complex other) {
mReal += other.mReal;
mImaginary += other.mImaginary;
}
// And so on and so forth
}
我知道我可以通过使它不可变来让生活变得更简单,但这意味着更多的对象创建和垃圾收集。有人知道在 Android 中这种创建和销毁的成本有多高吗? (不仅是最新版本;我还想支持设备 运行 2.x。)
我的建议是不要担心这个并继续使用不可变对象创建应用程序。
whether you should worry about this is completely dependent on where and when you create these objects
我的评论更旨在询问您是否想在应用程序的关键点(例如在绘制过程中)进行昂贵的操作。听起来好像你不是。
有趣的是,根据我的经验,使用不可变对象模式并未对我开发的应用程序的内存或性能产生明显影响。也就是说,虽然可能会产生影响,但这从来都不是明显放缓的原因。
(无可否认,我的专业经验跨越 API 14+。)