gpt4 book ai didi

java - Android 中的不可变对象(immutable对象)有多昂贵?

转载 作者:行者123 更新时间:2023-11-30 01:44:02 27 4
gpt4 key购买 nike

假设我想创建一个类来表示复数。该对象只包含两个 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 的设备。)

最佳答案

我的建议是不要担心这个并继续使用不可变对象(immutable对象)创建应用程序。

whether you should worry about this is completely dependent on where and when you create these objects

我的评论更旨在询问您是否想在应用程序的关键点(例如在绘制过程中)执行昂贵的操作。听起来好像你不是。

有趣的是,根据我的经验,使用不可变对象(immutable对象)模式并未对我开发的应用程序的内存或性能产生明显影响。也就是说,虽然可能会产生影响,但这从来都不是明显放缓的原因。

(诚然,我的专业经验涵盖 API 14+。)

关于java - Android 中的不可变对象(immutable对象)有多昂贵?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33986183/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com