2

The question was arisen about an array of objects when it's more in the source code than it's required. For example, I have Button objects like this(not initialized yet):

Button[] buttons = new Button[99]

So the question is that if I create and initialize say for instance only 10 of them, will there be any additional memory consumption because of the 99 array of buttons?

3
  • 5
    the array will hold its size to the references - it depends if Button is a value or reference type Commented Aug 6, 2020 at 15:29
  • If you don't know how many buttons you'll use, you can consider using a List. It'll double in size once a certain limit is reached. Commented Aug 6, 2020 at 15:32
  • @daniel-a-white, what do you mean by if it's value? Commented Aug 6, 2020 at 21:50

1 Answer 1

4

The answer is: Yes, some additional space will be wasted - but it's not very much.

Assuming a Button is a reference type, the space used for the array is numberOfElements * size of a reference when you first create the array without creating any Button objects.

The size of a reference is, of course, 32 bits when running as a 32-bit process and 64 bits when running as a 64-bit process.

So for your example with 10 buttons in an array sized for 99, the total space taken for a 64-bit process would be:

Size of the array + 10 * (size of a Button)

Where the size of the array would be 99 * size of a reference, or 99 * 8 (bytes).

(The 8 bytes in that calculation is because 64 bits == 8 bytes)

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

1 Comment

@ДмитрийИгнатьев See here for example. The new operator automatically initializes the elements of an array to their default value, which, for example, is zero for all numeric types and null for all reference types. - this tells you that all the elements are initialised to a null reference, from which you can tell the size of the array will be #elements * sizeof(reference)

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.