Understanding bitwise operations in javascript

后端 未结 4 1529
时光说笑
时光说笑 2020-12-15 01:36

I am currently storing data inside an XML doc as binary, 20 digits long, each representing a boolean value.



        
4条回答
  •  青春惊慌失措
    2020-12-15 02:37

    Be extremely wary. Javascript does not have integers -- numbers are stored as 64 bit floating-point. You should get accurate conversion out to 52 bits. If you get more flags than that, bad things will happen as your "number" gets rounded to the nearest representable floating-point number. (ouch!)

    Also, bitwise manipulation will not help performance, because the floating point number will be converted to an integer, tested, and then converted back.

    If you have several places that you want to check the flags, I'd set the flags on an object, preferably with names, like so:

    var flags = {};
    flags.use_apples = map.charAt(4);
    flags.use_bananas = map.charAt(10);
    

    etc...

    Then you can test those flags inside your loop:

    if(flags.use_apples) {
        do_apple_thing();
    }
    

    An object slot test will be faster than a bitwise check, since Javascript is not optimized for bitwise operators. However, if your loop is slow, I fear that decoding these flags is probably not the source of the slowness.

提交回复
热议问题