Unity ToLua 性能优化(三)值类型参数传递
- lua获取c#对象的时候,tolua会把对象放到ObjectTranslator中的一个Dictionary中,然后返回一个id给lua。 Dictionary避免c#对象被垃圾回收同时,后面也可以根据id来取回对象
public readonly Dictionary<object, int> objectsBackMap = new Dictionary<object, int>(new CompareObject());
- 这里Dictionary存的是object类型,所有的class的基类. 但是在碰到值类型(如:Vector3)的时候这里就有装箱和拆箱操作,会产生gc
Vector3(栈)转为object类型需要boxing(堆内存中),object转回Vector3需要unboxing,使用后释放该object引用,这个堆内存被gc检测到已经没引用,释放该堆内存,产生一个gc内存
- 为了避免该情况可以针对相应的值类型做以下处理避免上述情况
static public void SetPosC(Component com, float x, float y, float z)
{
com.transform.localPosition = new Vector3( x, y, z);
}
static public void GetPosC(Component com, out float x, out float y, out float z)
{
Vector3 pos = com.transform.localPosition;
x = pos.x;
y = pos.y;
z = pos.z;
}
- 以上只是用Vector3举例,实际tolua中对一些常用的值类型有优化处理(见LuaInterface.LuaValueType)
public const int None = 0;
public const int Vector3 = 1;
public const int Quaternion = 2;
public const int Vector2 = 3;
public const int Color = 4;
public const int Vector4 = 5;
public const int Ray = 6;
public const int Bounds = 7;
public const int Touch = 8;
public const int LayerMask = 9;
public const int RaycastHit = 10;
public const int Int64 = 11;
public const int UInt64 = 12;
public const int Max = 64;