我知道本地声明的变量被编译成与 StackOverflow 答案基本相同的代码 here .但是,它不包括创建和使用静态对象,尤其是 Unity 对象。我对 C# 的了解是临时从 C++ 而来,然后直接跳到 Unity,过去的实践让我看到我使用临时变量而不是很好命名的变量。我想在我的下一个项目中使用更好的实践,其中可读性显然很有值(value),但性能更重要。所以考虑这两段代码......
静态温度...
public class Shot : MonoBehaviour {
static Actor tempActor;
static Vector3 tempVec;
static float tempFloat;
static HitResult hitResult;
public float damage;
public float unblockable;
public Vector3 originationPoint;
private void OnTriggerEnter(Collider collision) {
if (collision.gameObject.layer == 11) {
tempActor = collision.gameObject.GetComponent<Actor>();
if (tempActor != null) {
tempVec = collision.transform.position - originationPoint;
// cast ray
originatorActor.RayDisableColliders();
bool rayHit = Physics.Raycast(originationPoint, tempVec, out hitResult, range, 1<<11, QueryTriggerInteraction.Ignore);
if (rayHit) {
if (hitResult.collider.gameObject.CompareTag("Hero") || hitResult.collider.gameObject.CompareTag("Villain")) {
tempActor = hitResult.collider.gameObject.GetComponent<Actor>();
tempActor.HitByShot(class_utilities.GetAngle(hitResult.transform, originationPoint), damage, unblockable);
}
}
originatorActor.RayEnableColliders();
}
}
}
}
根据本地声明的温度
public class Shot : MonoBehaviour {
public float damage;
public float unblockable;
public Vector3 originationPoint;
private void OnTriggerEnter(Collider collision) {
if (collision.gameObject.layer == 11) {
Actor tempActor = collision.gameObject.GetComponent<Actor>();
if (tempActor != null) {
Vector3 offset = collision.transform.position - originationPoint;
// cast ray
originatorActor.RayDisableColliders();
HitResult hitResult;
bool rayHit = Physics.Raycast(originationPoint, offset, out hitResult, range, 1<<11, QueryTriggerInteraction.Ignore);
if (rayHit) {
if (hitResult.collider.gameObject.CompareTag("Hero") || hitResult.collider.gameObject.CompareTag("Villain")) {
tempActor = hitResult.collider.gameObject.GetComponent<Actor>();
tempActor.HitByShot(class_utilities.GetAngle(hitResult.transform, originationPoint), damage, unblockable);
}
}
originatorActor.RayEnableColliders();
}
}
}
}
这两种方法在性能方面是否存在差异,尤其是在我看来内存分配和垃圾回收方面?
最佳答案
最大的问题不是性能,而是正确性。以这种方式使用静态字段会改变含义,并可能导致以下任一方面的大问题:
- 多个线程访问相同的静态值并在进程中互相踩踏
- 作为一种特殊情况,这不仅会导致意外 值,还会导致“撕裂”值,因为您提到了像
Vector3
- 作为一种特殊情况,这不仅会导致意外 值,还会导致“撕裂”值,因为您提到了像
- 调用重入的任何东西;调用堆栈中的每个方法都会在不考虑任何预期行为的情况下踩踏该值
基本上:除非你有很好的理由,否则不要这样做(即不要为临时本地人滥用静态字段);改用常规局部变量。
Is there any difference in terms of performance
速度方面,几乎可以肯定不是,但你必须用 benchmarkdotnet 之类的东西来衡量它
notably to my mind memory allocation and garbage collection
通过将值放入静态字段,您可以使该值可访问任何对象:可访问。如果您从不清除该字段,它可能会不必要地使任意大的对象图保持事件状态。
关于c# - 在 C# (Unity) 中使用静态临时变量有什么好处吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57432262/