Static method is slow

I am programming a simple game in java. I checked the collision with 30 FPS where I needed to get the window size. Since I did not have access to the GUI instance, I thought I would make a shared instance because it is pretty standard in Objective-C, where I came from.

class GUI extends JFrame { private static GUI _sharedInstance; public static GUI sharedInstance() { if (_sharedInstance == null) { _sharedInstance = new GUI(); } return _sharedInstance; } } 

But for some reason it was very slow. Then I replaced the shared instance with instances of public static final for size, and it works fast, even with 60 FPS or higher.

Can someone explain to me why this is happening?

EDIT

So instead of calling GUI.sharedInstance().getWidth() I just call GUI.windowSize.width . Instead, I used public static final Dimension windowSize .

EDIT

Here is a collision detection. So, instead of calling int width = GUI.kWindowWidth; , I used to call int width = GUI.sharedInstance().getWidth(); .

 // Appears on other side if (kAppearsOnOtherSide) { int width = GUI.kWindowWidth; int height = GUI.kWindowHeight; // Slow // int width = GUI.sharedInstance().getWidth(); // int width = GUI.sharedInstance().getHeight(); Point p = this.getSnakeHead().getLocation(); int headX = px; int headY = py; if (headX >= width) { this.getSnakeHead().setLocation(new Point(headX - width, headY)); } else if (headX < 0) { this.getSnakeHead().setLocation(new Point(headX + width, headY)); } else if (headY >= height) { this.getSnakeHead().setLocation(new Point(headX, headY - height)); } else if (headY < 0) { this.getSnakeHead().setLocation(new Point(headX, headY + height)); } } 
+6
source share
1 answer

I know that this may not be the real answer to the question, but there may be a problem with the state of the race. I assume that you are trying to use the lazy / singleton template because building a GUI class is quite expensive and you only need one instance.

Now what is going on? If a thread executes in the body of an if , it creates a new instance of the GUI . Before the next appointment, he is suspended by the scheduler. Now another thread appears, he sees that _sharedInstance is still null and creates another instance of the GUI (and so on ...).

Suppose that there are only two threads. The first thread ends, and the second continues, now you have two instances of the GUI class. No one says that an undirected GUI instance is being destroyed or garbage is being collected. This may explain a 50% performance loss compared to using finally and assigning a GUI instance directly to _sharedInstance .

See Java examples at http://en.wikipedia.org/wiki/Singleton_pattern Double checked locks, inner classes, or an enumeration are the ways you can use.

+3
source

All Articles