请看一下这段代码:
public static function getCharLocationById(id:int):Point {
var lx:int = id % 16;
var ly:int = id / 16;
return new Point(lx, ly);
}
它工作得很好但很慢。有没有人知道如何让它更快?
提前致谢!
答案 0 :(得分:2)
如果你事先为所有可能性创建了对象,你所要做的就是在数组中查找它们(id为索引)。
private static const _locationLookUpTable:Array = []; //or Vector, if you like
// fill the array somewhere, maybe like this
for (var i:uint = 0; i <= maximumId; ++i) _locationLookUpTable.push(i % 16, i / 16);
public static function getCharLocationById(id:int):Point {
return _locationLookUpTable[id];
}
如果id的数量不受限制或非常大,则可以使用对象池。 这需要更多代码,因为如果不再使用它们,应该将对象返回到池中。
答案 1 :(得分:0)
忽略变量创建,只需要时间来创建,分配然后再次读取它们以将它们提交给Point
构造函数。
public static function getCharLocationById(id:int):Point
{
return new Point(id % 16, id / 16);
}
另外,考虑到你的输入是一个整数,你可以使用16位除法的位移,如下所示:
id = id >> 1; // div. by 2 = id/2
id = id >> 1; // div. by 2 = id/2/2 = id/4
id = id >> 1; // div. by 2 = id/2/2/2 = id/8
id = id >> 1; // div. by 2 = id/2/2/2/2 = id/16
缩短我们得到的
id = id >> 4; // (1+1+1+1 = 4)
请注意,结果也是整数,因此11 >> 1
将返回5
而不会 5.5
。