Search code examples
dartintsize

What is the size of an integer variable in Dart


In Dart site they said that the integer size is 64 bit , is this the max size of an integer, or this is the size of any integer even if the integer is a small number such as 12?

If every integer size is 64 bit , does this affect the performance of the application?


Solution

  • The answer is: "It depends".

    First of all, if you compile Dart to JavaScript, all Dart numbers (int and double values) are represented by JavaScript Numbers. That means that all Dart numbers are Dart doubles. Even the integers, they just happen to be non-fractional doubles, and therefore can have at most 53 bits of precision. So, on the web, an int value implements double as well.

    The native (non-web) Dart ints are 64-bit two's complement integers. The VM may represent some of them as smaller numbers internally if it can see an advantage in that, but that's an implementation detail that you shouldn't be able to see.

    On a 64-bit VM, all pointers are 64 bits, so you can't directly store anything smaller than that in the Dart heap (at least outside of typed-data lists). Still, if your value is a 63-bit signed integer, the VM can store it directly in a pointer (a so-called "small integer" or "smi"), otherwise it has to allocate a heap object to store the 64 bits, so that it can still tell the difference between an integer and a heap pointer. That's important for garbage collection.

    On a 32-bit VM, all pointers are 32 bits, and if your integer is a 31-bit signed integer, it can be stored in the pointer, otherwise it becomes a heap object.

    That's for storing numbers where you can read them back later from somewhere else. For a local variable inside a function, where the VM knows all the ways it's accessed, the VM can choose to unbox the value, storing plain integers on the stack instead of heap-numbers or tagged small integers. If the compiler knows that you only use 16-bit integers, it can (theoretically) use only 16 bits for it. In practice, anything smaller than 32 bits is probably less efficient.

    These optimizations happen for performance reasons, so yes, it affects performance, and the compiler tries to avoid unnecessary overheads.

    That's the current implementation. It can change at any time as long as you can't tell the difference when running your program.