Search code examples
dartcompilationinteger-division

Is integer division operator necessary in Dart?


Is the integer division operator any different that casting the result of normal division?

Consider the following Dart code:

void main() {
  
  int a = 10;
  int b = 3;
  
  int result = a~/b;
  int result2 = (a/b).toInt();
  
}

Do both of those expressions compile to the same machine code? I'm assuming the answer would be either:

A) Yes, but only because the compiler is smart enough to re-write the second expression.

B) Yes, because there is no actual difference and the first expression is shorthand for the second.

or C) No, because there is a difference in the way the calculation is performed at the CPU level and the compiler doesn't optimize this for you.


Solution

  • x ~/ y is not equivalent to (x / y).toInt(). Integer arithmetic (including division) should1 be significantly faster than floating-point arithmetic.

    If x ~/ y is faster, then couldn't the compiler automatically make that transformation? Perhaps, but such a transformation wouldn't always generate the same results, so it wouldn't necessarily be appropriate. Integer division typically is used when the operands are integers. (That is, when you start in the integer domain and want to stay in the integer domain.) If the operands are integers, then the two operations can generate different results due to the difference in precision between int (64-bit signed integers for the Dart VM) and double (a IEEE-754 double-precision floating-point number, which has 53 bits of precision for its significand):

    void main() {
      var x = 9223372036854775801; // Close to (but not exactly) 2^63 - 1
      print(x);               // Prints: 9223372036854775801
      print(x ~/ 1);          // Prints: 9223372036854775801
      print((x / 1).toInt()); // Prints: 9223372036854775807
    }
    

    Finally, (x / y).toInt() is simply more cumbersome to write and to read than x ~/ y, especially if it's part of a more complex arithmetic expression.


    1 In practice, it turns out there isn't much of a performance difference. See https://github.com/dart-lang/sdk/issues/46855.