gpt4 book ai didi

java - 静态方法很慢

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:26:16 24 4
gpt4 key购买 nike

我正在用 Java 编写一个简单的游戏。我用 30 FPS 进行了碰撞测试,我必须在其中获得窗口的大小。因为我无法访问 GUI 实例,所以我想创建一个共享实例,因为这在我来自的 Objective-C 中是非常标准的。

class GUI extends JFrame {
private static GUI _sharedInstance;

public static GUI sharedInstance() {
if (_sharedInstance == null) {
_sharedInstance = new GUI();
}
return _sharedInstance;
}
}

但是由于某些原因,它真的很慢。然后我将共享实例替换为 public static final 大小的实例,现在它运行速度很快,即使是 60 FPS 或更高。

谁能解释一下为什么会这样?

编辑

因此,我没有调用 GUI.sharedInstance().getWidth(),而是调用了 GUI.windowSize.width。我改用了 public static final Dimension windowSize

编辑

这是碰撞检测。因此,不是调用 int width = GUI.kWindowWidth;,我之前调用了 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 = p.x;
int headY = p.y;

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

最佳答案

我知道这可能不是问题的真正答案,但竞争条件可能存在问题。我假设您正在尝试使用惰性/单例模式,因为 GUI 类的构建非常昂贵,而且您只需要一个实例。

现在,会发生什么?如果线程运行到 if 语句体,它会创建一个新的 GUI 实例。就在下一次分配之前,它会被调度程序暂停。现在另一个线程弹出,看到 _sharedInstance 仍然是 null 并创建另一个 GUI 实例(等等...)。

让我们假设只有两个线程。第一个线程运行到最后,第二个线程继续,现在你有两个 GUI 类的实例。没有人说未分配的 GUI 实例被销毁或垃圾​​收集。与使用 finally 并将 GUI 实例直接分配给 _sharedInstance 相比,这可以解释 50% 的性能损失。

参见例如http://en.wikipedia.org/wiki/Singleton_pattern 处的 Java 示例双重检查锁定、内部类或枚举是您可以使用的方式。

关于java - 静态方法很慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13521055/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com