2

Say I have a list of strings or whatever really. Then say I want to use ONE of the strings multiple times in the next bit of code. Should I create a new String variable foo String foo = list.get(position) and use foo in the following code, or should I save the memory space and use list.get(position) every time I need to use that string? Or are they actually the same thing under the hood?

Would the answer change if the list contained a more complicated class that might do a lot of computations to instantiate or have a lot of variables in itself so creating a new one takes up a lot of memory?

0

2 Answers 2

7

The list only holds references to the items it contains, not the items themselves.

When you write SomeObject s = list.get(0); you simply retrieve a reference to the object and the memory used is either 32 or 64 bits depending on the device. And since the get operations is extremely fast (essentially an array access), the answer is that it makes almost no difference* (but using a variable might be slightly faster).

From a readability perspective it is generally better to use an extra variable and give it a self-explanatory name.

*assuming you use an ArrayList: for other list implementations, the cost of a get might be significant.

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

6 Comments

I agree that from readability perspective it is more convenient to use an intermediate variable, but when you use extra variable, you allocate one extra object on the heap - one extra string
No you don't - as explained in my answer a variable is a reference (= pointer) to an object not the object itself. In String s = "ABC"; String s2 = s; there is only one string object, but two references to it.
If the list is, by any chance, shared across threads - better to get the reference & hold for the immediate "use case".
Your initial analysis assumes an ArrayList, but doesn't hold for a LinkedList. It's just better to grab the value and hold the reference.
@RichardSitze yes indeed.
|
4

Get the value once, and hold it for the life of your use-case:

  1. The memory cost for holding a reference is minimal, and less than the cost, in byte-code, of N extra invocations of list.get(0) for some small N (likely 2, if not 1). Granted, the cost may be in a different area of memory.

  2. The runtime cost for list.get(0) should not be assumed to be very fast (O(1)). Such an assumption is based on an underlying ArrayList; it's O(N) for a LinkedList.

  3. If your code does, or ever will, run in a multi-threaded environment, then:

    • list may change behind the scenes.

    • The cost of a (protected) get will go up.

  4. As mentioned by assylias, it's better style to give the value a meaningful name.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.