What is fastest way to convert bool to byte?

前端 未结 9 1672
悲哀的现实
悲哀的现实 2020-12-15 06:23

What is fastest way to convert bool to byte?

I want this mapping: False=0, True=1

Note: I don\'t want to use any if statements or other conditio

9条回答
  •  -上瘾入骨i
    2020-12-15 06:39

    The following is a simple benchmark to compare the three options:

        Int32 j = 0;
        bool b = true;
    
        for (int n = 0; n < 5; n++) {
            Stopwatch sw1 = new Stopwatch();
            Stopwatch sw2 = new Stopwatch();
            Stopwatch sw3 = new Stopwatch();
            sw1.Start();
            for (int i = 100 * 1000 * 1000; i > 0; i--)
                unsafe { j = *(int*)(&b); }
            sw1.Stop();
    
            sw2.Start();
            for (int i = 100 * 1000 * 1000; i > 0; i--)
                j = b ? 1 : 0;
            sw2.Stop();
    
            sw3.Start();
            for (int i = 100 * 1000 * 1000; i > 0; i--)
                j = Convert.ToInt32(b);
            sw3.Stop();
            Trace.WriteLine("sw1: " + sw1.ElapsedMilliseconds +
                "  sw2:" + sw2.ElapsedMilliseconds + ", +" + 100 * (sw2.ElapsedMilliseconds - sw1.ElapsedMilliseconds) / sw1.ElapsedMilliseconds + "% relative to sw1" +
                "  sw3:" + sw3.ElapsedMilliseconds + ", +" + 100 * (sw3.ElapsedMilliseconds - sw1.ElapsedMilliseconds) / sw1.ElapsedMilliseconds + "% relative to sw1"
                );
        }
    

    The results:

    sw1: 172  sw2:218, +26% relative to sw1  sw3:213, +23% relative to sw1
    sw1: 168  sw2:211, +25% relative to sw1  sw3:211, +25% relative to sw1
    sw1: 167  sw2:212, +26% relative to sw1  sw3:208, +24% relative to sw1
    sw1: 167  sw2:211, +26% relative to sw1  sw3:209, +25% relative to sw1
    sw1: 167  sw2:212, +26% relative to sw1  sw3:210, +25% relative to sw1
    

    Conclusion:

    The unsafe method is about 25% faster than the other two!

    The relative slowness of the "if" version is due to the high cost of branching. The cost of the Convert could have been avoided if Microsoft would do the conversion at compile time..

提交回复
热议问题