Gideon
Gideon

Reputation: 2014

Does setting a object to null multiple times have a performance impact?

I am making a game in java that is using a 'tail' behind the mouse. I use a MouseMotionListener and use the mouseDragged(MouseEvent e) function to add locations of the mouse to an array.

So as long as the mouseDragged(MouseEvent e) function is fired, it should add the current mouse location to an array, when the dragging is stopped, the array should be cleared.

My idea was to use the mouseMoved(MouseEvent e) function to set the array to null. I can do this like this:

public void mouseMoved(MouseEvent e) {
    if(myTailArray != null) {
        myTailArray = null;
    }
}

Or just like this:

public void mouseMoved(MouseEvent e) {
    myTailArray = null;
}

The last method means that myTailArray will be set to null a lot of times for nothing. But does it make a difference performance wise?

EDIT: Just to be clear, I know this can cause bugs when the mouse isn't moved after a drag. I use a MouseListener to reset on the press and release of the mouse, but I was just curious.

EDIT2: Thanks for all the comments! I thought because the event is fired 'quite a lot' it maybe would be a bad smell in my code. Though I haven't thought about caching etc.

Upvotes: 1

Views: 140

Answers (5)

Jason C
Jason C

Reputation: 40315

Obviously not, as you had to come here and ask after being unable to notice a difference in your programs actual performance. :)

The point is, unless it isn't meeting your performance requirements, it isn't worth optimizing.

In any case, the performance difference of doing an extra assignment vs a branch is completely negligible compared to e.g. the time spent generating and handling a mouse move event.

Think about it (simplified):

  1. User decides to move the mouse.
  2. Users brain sends electrical impulse to muscles in arm and hand via chains of sodium/potassium reactions.
  3. Force from muscle movement overcomes friction of mouse on table, mouse moves.
  4. Optical mouse samples images on table, compares consecutive images in hardware and calculates an offset.
  5. Movement data serialized and sent over USB, various synchronization occurs.
  6. Hardware interrupts generated and handled, incoming data read, buffered, dispatched to appropriate driver.
  7. Mouse position updated. Cursor redrawn by blitting and modifying blocks of data in video memory.
  8. Window system checks its windows, checking mouse state and dispatching events to synchronized thread queues.
  9. Swing window receives native events, checks own internal state, translates to Swing events and dispatches messages through object tree, eventually resulting in...
  10. Your mouse move handler being called.

So why are you worried about a few nanoseconds difference in an assignment or a branch? Just the stack cleanup code in the method call itself will dwarf your assignment.

Edit: By the way, here is a somewhat dated but still valid great article about micro-tuning: http://www.onjava.com/pub/a/onjava/2002/03/20/optimization.html

One of the key points there is "Always set a target before starting tuning, so that you know when to stop." Not only does the article have a nice case study you can work along with, it finishes with a nice outline of a general procedure: Identify the bottleneck, set a target, test, profile, and optimize accordingly.

Upvotes: 3

Hot Licks
Hot Licks

Reputation: 47699

The only case where the second (and generally preferred) approach would be slower would be in an intensely-multithreaded environment where redundantly setting to null results in changed pages and resulting cache thrashing. It happens, but if you were in that situation you'd very likely already be aware of the potential problem.

Upvotes: 0

Gustek
Gustek

Reputation: 3760

If it has any impact at all You won't notice it anyway.

But the version without if statement should be "faster" as comparison is more expensive than assignment. (I remember that from uni Though can't find any reference to prove it)

Upvotes: 0

Marko Topolnik
Marko Topolnik

Reputation: 200138

Setting a non-volatile instance variable takes a negligible amount of time: it's just a local CPU cache write operation, without any expensive memory barrier instructions. Depending on circumstances, some writes may be completely eliminated by the JIT compiler.

But just to put these things into perspective, I should add that we are discussing 0.5 ns vs. maybe 10 ns worst-case scenario with full volatile write. Just calling the method may take more time than the write itself. A mouse generates 100 reports per second at most—that's 100 x 10ns = 1 µs of time taken (worst-case!) within each second of wall-clock time.

Upvotes: 2

Mike Strobel
Mike Strobel

Reputation: 25623

This sort of thing is a micro-optimization that you should not concern yourself with. If there is a difference, it will be negligible, even if the method is invoked thousands of times. It may not even be the difference you expect: depending on how often the value is null or non-null, the added branch instruction may outweigh the redundant assignment (branches are relatively expensive on many architectures).

Generally, attempting to optimize this sort of thing without having demonstrated a real-world performance issue is counterproductive.

Upvotes: 2

Related Questions