Java-Gaming.org Hi !
Featured games (83)
games approved by the League of Dukes
Games in Showcase (516)
Games in Android Showcase (123)
games submitted by our members
Games in WIP (577)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1] 2
  ignore  |  Print  
  clearing or make new array?  (Read 5743 times)
0 Members and 1 Guest are viewing this topic.
Offline Rakiayn

Senior Newbie





« Posted 2014-02-10 23:02:35 »

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.

1  
2  
3  
4  
5  
6  
7  
    public void deleteactor() 
    {
        for (int l = 0; l < (listoftags.length); l++)
        {          
            listoftags[l]="";          
        }
    }


or

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
    public void recycleobject()
{
}
    public void deleteactor()
    {
        for (int l = 0; l < (listoftags.length); l++)
        {          
            listoftags[l]="";          
        }
    }
Offline Danny02
« Reply #1 - Posted 2014-02-10 23:04:55 »

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

JGO Kernel


Medals: 156
Projects: 7
Exp: 3 years


JumpButton Studios


« Reply #2 - Posted 2014-02-10 23:05:28 »

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

Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline kingroka123

JGO Ninja


Medals: 36
Projects: 6
Exp: 1 year


Gamer's Helmet


« Reply #3 - Posted 2014-02-10 23:06:55 »

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
1  
listoftags[l]=""; 
use
1  
listoftags[l]=null; 


Offline Rakiayn

Senior Newbie





« Reply #4 - Posted 2014-02-10 23:08:35 »

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.

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
    public void recycleobject()
    {
      //do stuff...
     
    }
    public void deleteactor()
    {
        for (int l = 0; l < (listoftags.length); l++)
        {          
            listoftags[l]="";          
        }
    }


or

1  
2  
3  
4  
5  
6  
7  
8  
9  
    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?

Offline opiop65

JGO Kernel


Medals: 156
Projects: 7
Exp: 3 years


JumpButton Studios


« Reply #5 - Posted 2014-02-10 23:10:43 »

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.

Offline Rakiayn

Senior Newbie





« Reply #6 - Posted 2014-02-10 23:15:12 »

So I should use the first option right?
Offline opiop65

JGO Kernel


Medals: 156
Projects: 7
Exp: 3 years


JumpButton Studios


« Reply #7 - Posted 2014-02-10 23:18:36 »

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.

Offline Rakiayn

Senior Newbie





« Reply #8 - Posted 2014-02-10 23:26:12 »

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.
Offline jonjava
« Reply #9 - Posted 2014-02-10 23:28:34 »

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.

Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline The Lion King
« Reply #10 - Posted 2014-02-10 23:32:07 »

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.

"You have to want it more than you want to breath, then you will be successful"
Offline Rakiayn

Senior Newbie





« Reply #11 - Posted 2014-02-10 23:38:04 »

so that would look like this?

1  
2  
3  
4  
5  
6  
7  
8  
9  
    public void recycleobject()
    {
         listoftags = new String[64];
         //do stuff...
    }
    public void deleteactor()
    {          
     
    }
Offline The Lion King
« Reply #12 - Posted 2014-02-10 23:39:43 »

If you insist on using the recycled, delete you would do it as you mentioned before
1  
2  
3  
4  
5  
6  
7  
8  
9  
public void recycleobject()
    {
         listoftags = new String[64];
         //do stuff...
    }
    public void deleteactor()
    {          
          listoftags = null;
    }

"You have to want it more than you want to breath, then you will be successful"
Offline jonjava
« Reply #13 - Posted 2014-02-10 23:43:11 »


Offline opiop65

JGO Kernel


Medals: 156
Projects: 7
Exp: 3 years


JumpButton Studios


« Reply #14 - Posted 2014-02-10 23:43:16 »

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

1  
public void recycleObject()



Offline ctomni231

JGO Wizard


Medals: 99
Projects: 1
Exp: 7 years


Not a glitch. Just have a lil' pixelexia...


« Reply #15 - Posted 2014-02-10 23:54:04 »

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...)

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
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.

Offline Rakiayn

Senior Newbie





« Reply #16 - Posted 2014-02-10 23:58:51 »

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

JGO Wizard


Medals: 99
Projects: 1
Exp: 7 years


Not a glitch. Just have a lil' pixelexia...


« Reply #17 - Posted 2014-02-11 00:18:10 »

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.

Offline TeamworkGuy2

Junior Duke


Medals: 10



« Reply #18 - Posted 2014-02-11 01:01:17 »

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.  Smiley

P.S. I know the feeling though, I still worry about optimization too early, even though I know I shouldn't.
Offline Cero
« Reply #19 - Posted 2014-02-11 01:48:32 »

^ this

Offline BurntPizza
« Reply #20 - Posted 2014-02-11 01:49:02 »

So basically Rakiayn, don't worry about clearing or 'deleting' your list of Strings, the JVM knows what it's doing better than you do, and the only time appropriate for a String pool is if you are generating millions of new strings all the time, which I doubt.

Also, is your program using too much memory? If not, don't fix it if it's not broken!

Nice article about Strings: http://java-performance.info/string-intern-in-java-6-7-8/
Offline gouessej
« Reply #21 - Posted 2014-02-11 11:28:32 »

Hi

Object pooling in Java has become completely useless and inefficient in most cases since Java 1.4. Rather avoid keeping references on useless objects so that the garbage collector can make a good job and implement some kind of management only for partially unmanaged objects allocated on the native heap which is the case of direct NIO buffers or objects depending on system resources (TeamworkGuy2 gave some examples).

If you poorly implement your object pool, it will be both useless and less effective than using no object pool at all. I agree with BurntPizza, "premature optimization is the root of all evil" (http://en.wikipedia.org/wiki/Program_optimization#cite_note-autogenerated268-2).

Offline Gibbo3771
« Reply #22 - Posted 2014-03-24 09:32:39 »

Object pooling in Java has become completely useless and inefficient in most cases since Java 1.4.

Was about to ask about this, I was considering doing it at one point for my game, rather than create objects over and over again, simply just put them into an array and respawn them.

Was pointless.

"This code works flawlessly first time and exactly how I wanted it"
Said no programmer ever
Offline princec

JGO Kernel


Medals: 409
Projects: 3
Exp: 16 years


Eh? Who? What? ... Me?


« Reply #23 - Posted 2014-03-24 17:01:08 »

I concur with these findings too; use pooling only when it is actually relatively expensive to construct an object (ie. large number of c'tor parameters, lots of validation, native call, large amount of memory consumed etc).

Cas Smiley

Offline loom_weaver

JGO Coder


Medals: 17



« Reply #24 - Posted 2014-03-24 17:50:44 »

Even something as simple as new MyClass(), while traditionally allocating object on the heap, might have the JVM put it on the stack instead (determined via escape analysis).

An interesting link:

Java theory and practice: Urban performance legends, revisited
http://www.ibm.com/developerworks/java/library/j-jtp09275/index.html
Offline princec

JGO Kernel


Medals: 409
Projects: 3
Exp: 16 years


Eh? Who? What? ... Me?


« Reply #25 - Posted 2014-03-24 20:19:22 »

Don't think scalar replacement is in yet.

Cas Smiley

Offline BurntPizza
« Reply #26 - Posted 2014-03-24 20:25:36 »

Don't think scalar replacement is in yet.

Cas Smiley

Apparently it's been in the server since JDK6U23, also how to tell whether it's working: http://www.java-gaming.org/index.php?topic=25533.0

Not sure about the client VM yet.
Offline princec

JGO Kernel


Medals: 409
Projects: 3
Exp: 16 years


Eh? Who? What? ... Me?


« Reply #27 - Posted 2014-03-25 09:33:39 »

Hmm it never seems to work for me. My heap was generating tens of thousands of $Itr classes (from foreach constructs) every frame. Unfortunately with all the other tiny objects I was making every frame that pushed GC over the edge of acceptable and started giving me the Dreaded Regular Pause, so I had to regress all my foreaches into ordinary for loops  Emo Still, pauses gone, wahey.

Cas Smiley

Offline jonjava
« Reply #28 - Posted 2014-03-25 09:52:38 »

Really? That sounds awful. Didn't realize foreach could be that bulky.

Offline princec

JGO Kernel


Medals: 409
Projects: 3
Exp: 16 years


Eh? Who? What? ... Me?


« Reply #29 - Posted 2014-03-25 10:03:36 »

Well, that's what I thought. I was fully expecting all the Itrs to be escape analysed and not even show up in visualVM but there they were, gobbling hundreds of K every frame.

Cas Smiley

Pages: [1] 2
  ignore  |  Print  
 
 

 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

TehJavaDev (33 views)
2014-10-27 03:28:38

TehJavaDev (26 views)
2014-10-27 03:27:51

DarkCart (41 views)
2014-10-26 19:37:11

Luminem (22 views)
2014-10-26 10:17:50

Luminem (27 views)
2014-10-26 10:14:04

theagentd (33 views)
2014-10-25 15:46:29

Longarmx (61 views)
2014-10-17 03:59:02

Norakomi (58 views)
2014-10-16 15:22:06

Norakomi (47 views)
2014-10-16 15:20:20

lcass (43 views)
2014-10-15 16:18:58
Understanding relations between setOrigin, setScale and setPosition in libGdx
by mbabuskov
2014-10-09 22:35:00

Definite guide to supporting multiple device resolutions on Android (2014)
by mbabuskov
2014-10-02 22:36:02

List of Learning Resources
by Longor1996
2014-08-16 10:40:00

List of Learning Resources
by SilverTiger
2014-08-05 19:33:27

Resources for WIP games
by CogWheelz
2014-08-01 16:20:17

Resources for WIP games
by CogWheelz
2014-08-01 16:19:50

List of Learning Resources
by SilverTiger
2014-07-31 16:29:50

List of Learning Resources
by SilverTiger
2014-07-31 16:26:06
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!