java - 更有效的处理方法?
问题描述
我目前正在开发 Java 在线游戏的扩展。我目前正在处理传送,以了解玩家是否已经传送了一定距离,该距离可能来自distance
参数。
问题是,我知道这是 CPU 上的一项超级密集的任务,即使我确实尝试从主线程中卸载它。
是否有更有效的方法来处理这个问题,或者我基本上必须重组整个事情?
this.square
就是 Math.pow();,this.sqrt
就是 Math.sqrt();,
this.hypot
如下:
default double hypot(double... numbers) {
double squaredSum = 0.0;
int length = numbers.length;
int count = 0;
while (count < length) {
double number = numbers[count];
squaredSum += Math.pow(number, 2.0);
++count;
}
return this.sqrt(squaredSum);
}
这就是我检查玩家是否传送的方式
public boolean anyNear(CustomLocation location, double distance) {
if (!this.locations.isEmpty()) {
Iterator<TeleportSnapshot> iterator = this.locations.iterator();
if (iterator.hasNext()) {
TeleportSnapshot teleport = iterator.next();
double deltaX = location.getX() - teleport.x;
double deltaY = location.getY() - teleport.y;
double deltaZ = location.getZ() - teleport.z;
while (!(this.hypot(deltaX, deltaY, deltaZ) < this.sqrt(this.square(distance)))) {
if (iterator.hasNext()) {
teleport = iterator.next();
deltaX = location.getX() - teleport.x;
deltaY = location.getY() - teleport.y;
deltaZ = location.getZ() - teleport.z;
} else {
return false;
}
}
return true;
} else {
return false;
}
} else {
return false;
}
}
解决方案
我同意大卫齐默尔曼的观点,你可能不应该在计算中使用平方根。
而不是做
sqrt(dx^2 + dy^2 + dz^2) < sqrt(distance^2),
您可以使用:
dx^2 + dy^2 + dz^2 < distance^2
这对 CPU 更友好。但是,假设的辅助函数的名称不再适合了...
推荐阅读
- laravel - 大数据的 Laravel 验证超时
- jquery - JQuery DataTable - 仅在创建新记录时将列设置为可编辑。但显示数据时不可编辑
- php - 使用 PDO 连接到 mySql 数据库时出现意外的“?>”
- security - 云漏洞扫描与管理查询
- python-3.x - 如何在 Python 中从头开始编码随机森林回归?
- c# - 如何使用 OAuth2 授权 Google 分析数据 API
- python - 与文本分类中的 LSTM 相比,CNN 给我更好的准确性是正常的吗?
- subset - AIMMS 如何获取一个索引的两个实例
- java - 我应该如何将代码放在 Java 的后台线程中?
- node.js - npm 错误!错误:EACCES:权限被拒绝