tkroman
tkroman

Reputation: 4798

What's more appropriate here: Arrays.copyOfRange() or ordinary loop?

Line 331 here (openjdk's MutableBigInteger source) defines function toIntArray(). In general, MutableBigInteger is an array that can be, for example {0, 0, 0, 0x12345678, ..., 0xffffffff, 0, 0, 0}, with variables offset and intLen defining positions of start and end of non-zero values (actual payload of array). So, that function goes as follows:

int[] result = new int[intLen];
for(int i=0; i<intLen; i++)
    result[i] = value[offset+i];
return result;

As package already imports Arrays utility class, isn't it better (faster? canonical?) to replace all the for-loop with Arrays.copyOfRange(value, offset, intLen);?

In general, my question is about all related situations: is it better to use library methods when dealing with cases like this or there is not actual difference and it results in executables of nearly same efficiency?

Upvotes: 1

Views: 740

Answers (2)

William Morrison
William Morrison

Reputation: 11006

I'd go with the library method not for efficiency but just for clean code.

Here's some information on copying arrays, very useful.

What I take away from that link is if you don't need the speed, don't bother changing it. The risk of introducing a bug and the tedium aren't worth it.

Upvotes: 1

Jon Kiparsky
Jon Kiparsky

Reputation: 7753

I'm not going to quibble with the openjdk implementation until I've spent some time profiling and figuring out why they might have made the decisions they made (they could be wrong, but my snap judgement is much more likely to be wrong).

However, as a rule, it is almost always better to use established libraries than your own home-rolled implementations.

Upvotes: 2

Related Questions