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)); } }
source share