简体   繁体   English

索引协调最佳实践? 按位运算与模和除法

[英]Indexing coordinate best practice? bitwise operation vs. modulo and division

While building my 2D game using unity, I started indexing my tiles coordinate for easy access in a dictionary with the following code: 在使用统一性构建2D游戏时,我开始用以下代码索引图块坐标以方便在字典中访问:

Public class Coordinate
{
    private short[] coordinate = new Int16[2];

    public Coordinate(In16 x, Int16 y)[...]
    public Int16 x {[...]}
    public Int16 y {[...]}

    public Int32 Key
    {
        get{
            return ((Int32)(y << 16) ^ x);
        }
    }

    public static void Coordinate(Coordinate coordinate, Int32 index)
    {
        coordinate.X = (Int16)(index >> 16);
        coordinate.y = (Int16)index;
    }
}

But eventually I found a quite simpler solution: 但是最终我找到了一个更简单的解决方案:

int index = y * mapWidth + x;

and

int x = index % mapWidth;
int y = index / mapWidth;

My question is this : Is any of these two method more safe for porting on different platform or just a better practice in general? 我的问题是:这两种方法中的任何一种在移植到不同平台上时是否更安全? If yes, is like to know the specifics. 如果是,则想了解具体情况。

Use Lsl or lsr is not a good practice because every body don't understand how it work even if it's faster than other solutions. 使用Lsl或lsr并不是一个好习惯,因为即使它比其他解决方案要快,每个人也不知道它是如何工作的。

Divisions are the worst solution because it's not natural for computers and they can take a lot of time (yeah less than 1 ms but too many time even so). 除法是最糟糕的解决方案,因为它对于计算机而言并不自然,并且会花费很多时间(是的,不到1毫秒,但即使这样也太多了)。 And imagine if you have a mapwith equal to 0. 想象一下,如果您有一个mapwith等于0。

i don't know for modulo but I think this is not a bad solution. 我不知道模数,但我认为这不是一个坏解决方案。

Multiplication can be the best solution or the worst. 乘法可能是最好的解决方案,也可能是最坏的解决方案。 It depend of the number (2^x = best solution, (2^x)-1= worst solution (I think this is right for arm assembly) it's like multiply by 3. In assembly you should multiply by 2 and add the number. x*3 = x*2 + x. For humans it's the same, not for computers. Maybe compiler make the transition because they are smarter than in the past. 它取决于数字(2 ^ x =最佳解决方案,(2 ^ x)-1 =最坏的解决方案(我认为这对手臂装配是正确的),就像乘以3。在装配中,您应该乘以2并加上数字。x * 3 = x * 2 + x。对于人类来说,是相同的,而不是对于计算机,也许是编译器进行了转换,因为它们比过去更智能。

In this case I think multiplications are the best solution. 在这种情况下,我认为乘法是最好的解决方案。 Just change << by a basic multiplication (2^16, so 65536) 只需将<<乘以基本乘法即可(2 ^ 16,所以65536)

I don't know what you want to do with your code but according to comments you should split index into 2 variables. 我不知道您想对代码做什么,但是根据注释,您应该将索引分为2个变量。 So vector2 is a good solution and easily to manage so a good practice. 因此,vector2是一个很好的解决方案,并且易于管理。

I'm sorry for my poor English. 对不起,我的英语不好。 If you don't understand something tell me I will try again :) 如果您不明白,请告诉我,我会再试一次:)

Have a nice day 祝你今天愉快

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM