Do I need more arrays of arrays of "non-zero" primitives?

Hi everyone, when you write an implementation of a list of arrays, I understand that to install Item(x) you must set it to null when deleting (and not just quantity -= 1 ) to prevent memory leak.

However, if my list of arrays is a list of primitive int arrays (with support for int[] ), does it make sense to set it to 0?

Similary, for a list of primitive character arrays (with char[] support), when RemoveRange () is called, does it make sense to populate this range with \u0000 ? Or is it quite normal to simply update length and pointers without changing the support array?

Is an array from int filled with zeros, possibly less memory footprint, than an array of equal length filled with integer values, since the runtime can do the optimization ?

+6
source share
6 answers

Is an array from int filled with zeros, possibly smaller than memory, than an array of the same length filled with integer values?

Assuming that in both cases we are dealing with int[] - no. Two arrays of the same type and the same length will always occupy the same amount of memory.

There is no need to rewrite your "empty" array elements with 0. This will not do any harm (besides the tiny performance advantage), and may even simplify the debugging process, but you do not need to.

+7
source

... when writing an implementation of a list of arrays, I understand that when deleting (and not just quantity -= 1 ) it is important to set Item(x) to null ) to prevent memory leak.

This is not true. Setting variables to null is not something that is always necessary, and not doing it does not mean that you have a memory leak.

However, if my list of arrays is a primitive list of int arrays, does it make sense to set it to 0?

No, for primitives it does not matter at all, 0 or \u0000 (for char) is just a value, like any other value. It does not take up less space.

+2
source

No, there is no need to do this with primitive types (that is, set them to 0), since the only reason “slots” are explicitly hidden is to prevent fake links to them, thereby twisting garbage collection.

+1
source

You cannot have an ArrayList<int> or any other container class with primitives. For simple arrays, see Jon Skeets answer.

+1
source

Primitives and references always occupy the same space.

+1
source

No, you need to collapse the object slot in the array to prevent leakage. If the object still refers to your array, then it cannot be GC'd - so you are referring to a leak.

Primitives, on the other hand, are still allocated on the stack, not the heap, so anyway GC'd. Primitives that are instances of class classes are stored as fields in the corresponding object and are cleared when the GC'd object.

In addition, JLS indicates that the primitive size is specific to the VM, but most (all?) Virtual machines currently support 4 int bytes. For more information, see JLS :

+1
source

Source: https://habr.com/ru/post/906387/


All Articles