1

In my class, I have a method that returns an array like this.

double arrValues[] = ClassX.getValues();

I wonder that, does the array size have any influence on performance. Are there any copy operation for arrValues[] or is it only a reference return ?

1
  • Your static method really should be returning a new copy of the array (unless, possibly, if it is of length zero). Commented Oct 23, 2009 at 12:44

3 Answers 3

3

In Java, Object types are returned by reference and primitive types are returned by value. Arrays are full blown Objects in Java. Therefore, in your example, the array is returned by reference and no copy is made.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 for why it is a reference rather than just stating it is a reference
3

It's only a reference (like everything except the basic types long, int, short, ...) in java is a only reference).

Comments

3

There's no information about the cost of constructing the array (how much that is affected by size is unknown).

Aside from that, what is returned is just a reference to the array constructed in getValues(), so the act of returning the array has no real performance impact.

4 Comments

In the absence of hardware assistance, and assuming a good GC, the amortized cost of allocating an N word array is the O(N) memory writes required to zero it.
I think I know what you mean, and I don't disagree. However, we don't know what the implementation of getValues() does. The "cost" I was talking about was not referring to the cost of doing "new Array[X]", rather its the cost of calculating the values that go into the array. How that scales... I don't know. However, that may not be the question the OP is asking...
getValues() only returns the array that is already constructed before. I wanted to ask only the cost of returning the array.
Ok, cool. It is usually a good question to ask because, very often, cached array's aren't returned (because the caller can then modify it). Usually a copy of an array is returned, or a new array is constructed. These are just valuable questions to answer when looking at performance.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.