tckmn
tckmn

Reputation: 59303

Useless variable in BigInteger class, why?

I was browsing through the Java code today and I noticed something.

int[] m = mag;
int len = m.length;
int[] xm = xInt.mag;
if (len != xm.length)
    return false;

(This is in the BigInteger class, which can be found by unzipping src.zip. It's in the equals method.) Why is an entirely new variable m created when it is only used once? Why isn't the code just int len = mag.length? I saw this in another method also (bitLength), and again, m is only used once. Is there any advantage to doing this or is it just a mistake by the creators of this class?

Edit: as @usernametbd pointed out, it is used a bit later:

for (int i = 0; i < len; i++)
    if (xm[i] != m[i])
        return false;

But they still could have just used mag. Why would an entirely new variable be made?

In a different function (in the same class, bitLength), a new variable m is made and it's only used a single time.

Upvotes: 4

Views: 196

Answers (4)

Hot Licks
Hot Licks

Reputation: 47739

Why is it important to you? The statement is not copying an array, just copying a reference -- a pointer. And "m" will likely be allocated into a register, whereas the JVM standard requires that "mag" must usually be refetched from the object -- the JITC can't freely optimize away field references.

Upvotes: 0

HRgiger
HRgiger

Reputation: 2790

When you call length (public final member variable of Array) via reflection which is constant time operation. But it is not same in C++. You have to get first array size in bytes and after divide this result to size of int to get exact value(Maybe there is better way). I think developer has the same reflex from him C++ times and carried value into local variable to use several times.

Upvotes: 0

Alexei Kaigorodov
Alexei Kaigorodov

Reputation: 13535

Because mag is a field, m is local variable. Access to local variable may be faster, though modern JITs can create such a substitute local variable automatically.

BTW you should have tell what the method you had in mind (I found it to be equals()), and cite original source (it is available) rather than decompiled one.

Upvotes: 2

username tbd
username tbd

Reputation: 9392

A bit (few lines) futher down, they use

for (int i = 0; i < len; i++)
    if (xm[i] != m[i])
        return false;

So m isn't completely isolated. They certainly could've used mag instead, but it's just a design choice.

Upvotes: 1

Related Questions