Why is if True slower than if 1?

True and False are not keywords in Python 2. They must resolve at runtime. This has been changed in Python 3 Same test on Python 3: >>> timeit.timeit(‘test1()’,setup=”from __main__ import test1″, number=10000000) 2.806439919999889 >>> timeit.timeit(‘test2()’,setup=”from __main__ import test2″, number=10000000) 2.801301520000038 >>> timeit.timeit(‘test3()’,setup=”from __main__ import test3″, number=10000000) 2.7952816800000164 >>> timeit.timeit(‘test4()’,setup=”from __main__ import test4″, number=10000000) 2.7862537199999906 Time … Read more

Is there any legitimate use of list[True], list[False] in Python?

In the past, some people have used this behaviour to produce a poor-man’s conditional expression: [‘foo’, ‘bar’][eggs > 5] # produces ‘bar’ when eggs is 6 or higher, ‘foo’ otherwise However, with a proper conditional expression having been added to the language in Python 2.5, this is very much frowned upon, for the reasons you … Read more

Primitive Boolean size in C#

In C#, certainly the bits aren’t packed by default, so multiple bool fields will each take 1 byte. You can use BitVector32, BitArray, or simply bitwise arithmetic to reduce this overhead. As variables I seem to recall they take 4 bytes (essentially handled as int = Int32). For example, the following sets i to 4: … Read more

Why the sizeof(bool) is not defined to be one, by the Standard itself?

The other likely size for it is that of int, being the “efficient” integer type for the platform. On architectures where it makes any difference whether the implementation chooses 1 or sizeof(int) there could be a trade-off between size (but if you’re happy to waste 7 bits per bool, why shouldn’t you be happy to … Read more