Efficiency Question?

If I have a grid and each position on grid is an ArrayList

is it better to

  1. Construct all the ArrayLists at initialization, and just leave them active, even if their is nothing in there.

  2. don’t make any ArrayList at initialization, but when an object moves to that spot, that instantiate an ArrayList and add it to the list, but if that object moves to a different grid, then delete that ArrayList, and make a new ArrayList, at that Enemies position

I’ve already done the first, and it works fine, but just wondering if is faster to do option 2.

If im understanding you, the only reason to do the latter is if you are trying to save memory.

If the grid is large then yes, construct them lazily.

Cas :slight_smile:

Oh was that what he was asking?

I thought he was asking if he should dereference the lists when empty.

but isn’t time consuming to recreate objects?

I read somewhere that instead of deleting an element in the list ( that you would need later, but not at the moment), its best to not delete it, but put it in a arrayList and pull it out of the arrayList when you need it.

im pretty sure that is faster than the first two,…right?

Most certainly even slower than reconstructing them.

Anyway… profile, then you don’t have to ask, because then you know it.

“Premature optimization is the root of all evil” [Tony Hoare]

Just optimize if you have a concrete performance-problem and do it after using a profiler :wink:

I totaly agree

Bruno

Java allocation is lightening fast. Collection of short lived objects is equally fast.

What you seem to be alluding to is “pooling”. On a modern (desktop) VM pooling almost never helps you, in fact it usually hurts you. The exceptions are (a) If the object being allocated needs to allocate a system construct such as a Thread or a Socket (the system is slow to give these to you) OR you have so over complicated a constructor that YOU are making allocation slow.

It sound like you’ve been listening to either very old advice or advice from C/C++ programmers.