结构VS班长寿命对象 [英] Struct vs Class for long lived objects

查看:116
本文介绍了结构VS班长寿命对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当你需要有非常小的物体,说是包含2个浮动属性,你将有百万人未会毁向右走,是结构更好的选择还是类?

When you need to have very small objects, say that contains 2 float property, and you will have millions of them that aren't gonna be "destroyed" right away, are structs a better choice or classes?

就像XNA作为一个库,有point3s等的结构,但如果你需要守住了很久的值,它会带来性能的威胁吗?

Like in xna as a library, there are point3s, etc as structs but if you need to hold onto those values for a long time, would it pose a performance threat?

推荐答案

相反,关于结构的大多数问题,其实这似乎是一个很好用的一个结构。如果它包含的数据是值类型,并且你要使用大量的这些,结构将工作做好

Contrary to most questions about structs, this actually seems to be a good use of a struct. If the data it contains are value types, and you are going to use a lot of these, a structure would work well.

一些提示:

::该结构应不大于16字节,或者你失去的性能优势。

:: The struct should not be larger than 16 bytes, or you lose the performance advantages.

::使结构不变。 。这使得使用更清晰。

:: Make the struct immutable. That makes the usage clearer.

例如:

public struct Point3D {

   public float X { get; private set; }
   public float Y { get; private set; }
   public float Z { get; private set; }

   public Point3D(float x, float y, float z) {
      X = x;
      Y = y;
      Z = z;
   }

   public Point3D Invert() {
      return new Point3D(-X, -Y, -Z);
   }

}

这篇关于结构VS班长寿命对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆