我是Java&我正在浏览图书馆,但我对两种方法感到困惑:
public class Complex {
/** The real part of a complex number. */
private double real;
/** The imaginary part of a complex number. */
private double imaginary;
public void divideComplex(Complex a, Complex b) {
this.real = a.real * b.real + a.imaginary * b.imaginary;
this.imaginary = a.imaginary * b.real - a.real * b.imaginary;
this.scaleComplex(this, b.squaredMagnitudeComplex());
}
public void scaleComplex(Complex a, double b) {
this.real = a.real / b;
this.imaginary = a.imaginary / b;
}
}
我在这里遗漏了什么或者不能divideComplex
这样做:
public void divideComplex(Complex a, Complex b) {
Complex newComplex = new Complex {
val real = this.real = a.real * b.real + a.imaginary * b.imaginary;
val imaginary = this.imaginary = a.imaginary * b.real - a.real * b.imaginary;
}
this.scaleComplex(newComplex, b.squaredMagnitudeComplex());
}
答案 0 :(得分:2)
原始代码与您的代码之间的区别在于原始代码会对调用Complex
的{{1}}进行更改,而您的代码不会更改它,因为它会创建一个新的本地代码divideComplex
。
但是,然后调用Complex
,它会覆盖当前对象的值。所以最后的结果确实相同。但是性能可能会有所不同:在您的代码中,创建并丢弃新对象,而原始代码就地工作而无需分配新内存。原始版本应该在内存使用和性能方面更高效(我说“应该”,因为JVM优化器不是那么可预测的。)