clearing or make new array?

Hi i have these objects that are beiing recycled all the time.
when these objects are ‘dead’ they go into a recycle pool and some array’s have to be cleared.



    public void deleteactor() 
    {
        for (int l = 0; l < (listoftags.length); l++) 
        {           
            listoftags[l]="";           
        }
    }


or



    public void recycleobject()
{
}
    public void deleteactor() 
    {
        for (int l = 0; l < (listoftags.length); l++) 
        {           
            listoftags[l]="";           
        }
    }

Do NOT recycle objects.
Do NOT use empty Strings as some sort of special value.

This doesn’t work. You cannot tell the GC (as far as I am aware) when to delete objects. Besides “” is still a value.

3 things:

first, What is your question exactly?

two, how is the first box of code different from the second in terms of actually doing something?

third, don’t use

listoftags[l]=""; 

use

listoftags[l]=null; 

sorry something went wrong while I was typing. The first post should be:

Hi i have these objects that are beiing recycled all the time.
when these objects are ‘dead’ they go into a recycle pool and some array’s have to be cleared.


    public void recycleobject()
    {
      //do stuff...
      
    }
    public void deleteactor() 
    {
        for (int l = 0; l < (listoftags.length); l++) 
        {           
            listoftags[l]="";           
        }
    }


or



    public void recycleobject()
    {
         listoftags = new String[64];
         //do stuff...
    }
    public void deleteactor() 
    {          
            listoftags = null;              
    }

in the first example the array is cleared but not deleted.
in the second it is deleted faster but it also has to be created again everytime the object is recycled.
should i use the first method or the second?

Like I said above, the GC only kicks in when it needs to. Java doesn’t let you specify (technically) when the GC kicks in. What you’re trying to do cannot be done reliably because Java takes control of collection. Sure, the array might be deleted quicker in some rare cases, but its not reliable. If you need manual GC, look into a C language.

So I should use the first option right?

I have no idea what you need this for, so I cannot recommend either. Both are “sketchy”, and you really do not need to worry about deleting objects. If you simply want to clear the object (assuming the array is taking in strings), then setting every element to “” would conceivably be ok, but that’s more of a personal coding style than anything.

I want a cleared string array when the object is recycled.
and btw the objects are never truly deleted. they are only active or inactive in the game.
when they become inactive I call the deleteactor method to clear/reset all their properties.
the recycleobject method reactivates the objects and put them back in the game.

Why do you need to “recycle” your object? What are you doing with the arrays?

There’s probably a much easier way to do what you’re trying to do. If you would care to explain what exactly that may be we would be able to help.

The second way is better and makes more sense. It is more obvious if you have some knowledge of pointers, but whenever you use new (even in java) it creates objects on the heap (a part of memory). The GC works by checking if there is a pointer to all objects in heap. The heap is unorganized and needs pointers to access elements. The second nothing points to an element in the heap, that element can not practically be used again, so the garbage collector deletes this object. Both ways will invoke the garbage collector to delete the old objects; however, the string “” is actually “\0” and takes up some memory and simply isn’t as logical as setting the array to null since you don’t want it to point at a ton of strings of “” you want it to point at nothing (null), and if you want to recycle it you just want to set a new array.

edit:
If you are setting the “Recycled” array back to the original array eventually. Why delete it? just leave it in memory? For example have a couple listOfTags arrays or even a multidimensional one if you want, and have 1 activeListOfTags array that you set to whever listOfTags is active at the time.

so that would look like this?


    public void recycleobject()
    {
         listoftags = new String[64];
         //do stuff...
    }
    public void deleteactor() 
    {          
     
    }

If you insist on using the recycled, delete you would do it as you mentioned before


public void recycleobject()
    {
         listoftags = new String[64];
         //do stuff...
    }
    public void deleteactor() 
    {          
          listoftags = null;
    }

By the way, by convention Java wants you to write your function names like this:


public void recycleObject()

Ugh, this sounds exactly like an Object Pool to me. But, then you wouldn’t need to delete the Objects, instead, you would just set them to a value that you wouldn’t use so they can be used again. Below is an implementation for objects (not written by me but borrowed…)


public abstract class ObjectPool<T>
{
    private static final int DEFAULT_INIT_SIZE = 10;
    private final ArrayList<T> collectedTrash;

    public ObjectPool()
    {
        this( DEFAULT_INIT_SIZE );
    }

    public ObjectPool( int initSize )
    {
        collectedTrash = new ArrayList<T>(initSize);
    }

    /**
     * Acquires an object from the pool, if a recycled one is available, then
     * the pool will return the recycled one rather than creating a new one.
     *
     * @return object instance
     */
    public final T acquireObject()
    {
        if( collectedTrash.size() > 0 )
            return collectedTrash.remove(0);
        else
            return createInstance();
    }

    /**
     * Releases an object and puts it into the object pool. The object pool
     * will recycle the object data in this step too.
     *
     * @param obj object instance
     */
    public final void releaseObject( T obj )
    {
        assert obj != null;

        collectedTrash.add( recycleInstance( obj ) );
    }

    /**
     * Recycles an used object back to a clean state, called by object pool
     * if a used object will released back to the pool.
     *
     * @param obj object instance
     * @return recycled instance of the object
     */
    protected abstract T recycleInstance( T obj );

    /**
     * Creates a new instance of that object class, called by the object pool
     * if no recycled instance is available in the collected released objects.
     *
     * @return clean object instance
     */
    protected abstract T createInstance();
}

As far as I know, this only works if you are trying to keep your memory under tight control. In most applications, this is just useless. There may be an ounce of speed to gain, but all-in-all uses for a pool is very limited and partial. Whatever you would need this system for is beyond me. The only time I used it was to keep too much particles from generating on the screen.

yes I do use an object pool.
I did that because I was/am afraid objects would not get garbaged collected

Well, to answer your question about when.

The instances were garbage collection happens the most is when Java is getting close to reaching its memory limit (high FPS), or in between long sleep cycles. With Java, your best bet is to not even worry about it and let Java do its job. I did a lot of playing around with particles and Java2D. This is an implementation of snow particles (literally the third time I used this example).

Snow Particles

It uses the two methods I stated. If you look at your profiler, you can also see exactly when Java uses the garbage collector. In simple programs, it isn’t worth it though. I usually only do it to put a cap on memory usage for objects, but I never worry about the garbage collector. Java knows when best to use it.

Well, now you have two implementations of an Object Pool. One in my snow code and one used with an ArrayList. To be honest, there is very minimal advantage for using an ObjectPool. What you gain in speed, you lose in space as these objects will need to have a fast live & die rate to take full advantage of it (like my snow particles). Anything else that has a slow live & die rate will just waste valuable space on your RAM.

In my case, particles work well with ObjectPool. However, I would have NPC objects be a basic ArrayList. My suggestion, just know what implementation is right for the job and use your best judgement.

I would reiterate what ctomni231 said, but my word isn’t all that important.
Instead I think a good source is Joshua Bloch’s ‘Effective Java’ handbook.

“avoiding object creation by maintaining your own object pool is a bad idea unless the objects in the pool are extremely heavyweight”
Bloch goes on to explain that extremely heavyweight is something like a reusable database connection or network socket.
Generally, “object pools clutters your code, increases memory footprint, and harms performance. Modern JVM implementations have highly optimized garbage collectors that easily outperform such object pools for lightweight objects.” -Item 5
Arrays of strings are about as lightweight as it gets, except for primitives such as byte, int, etc.

The book further mentions that “It is a very bad idea to warp an API to achieve good performance.” -Item 55
The type of warped API the book is talking about is a class, package, set of methods, etc. which include methods or classes aimed to improve performance but that reduce code readability.
Adding a recycleObject() or deleteObject() method to an object shouldn’t be necessary unless the object uses a system resource such as a video card, sound input/output device, network socket, hard drive file, etc.

Programming tends to be a trade off between time, performance, quality, and half a dozen other factors.
Your time is important and adding performance optimizations too early wastes time.

Write a well structures program and if performance issues come up, do some profiling and discover which parts of your code are slow, only then should you start trying to optimize.
DON’T WORRY ABOUT PERFORMANCE UNTIL YOU HAVE SOMETHING MOSTLY DONE.
I try to never shouting, but I’ve wasted weeks of my life prematurely optimizing code and it’s useless; don’t do it, you’ll be a happier, more productive developer for it. :slight_smile:

P.S. I know the feeling though, I still worry about optimization too early, even though I know I shouldn’t.

^ this