optimizationdart

How can I optimize Dart code heavy on if statements?


I'm new to the Dart programming language, and I turned to my usual test, FizzBuzz, to check out the language. At the moment, I've got this relatively if-heavy example, which is pretty slow. Just dropping one if statements takes the execution time from 36 seconds to 25 seconds on my MacBook Pro, with 5000000 loops. I was wondering the ways I could optimize it further.

void main() {
  for (int i = 0; i < 5000000; i++) {
    var num = i + 1;
    if (num % 15 == 0) {
      print('FizzBuzz');
      continue;
    }
    if (num % 5 == 0) {
      print('Buzz');
      continue;
    }
    if (num % 3 == 0) {
      print('Fizz');
      continue;
    }
    print(num);
  }
}

I tried wrapping it all in a switch statement, as follows, but it doesn't compile to JS, and DartPad gives the error Type 'int' of the switch expression isn't assignable to the type 'bool' of case expressions.

void main() {
  for (int i = 0; i < 5000000; i++) {
    var num = i + 1;
    switch (num) {
      case (num % 15 == 0):
        print('FizzBuzz');
        break;
      case (num % 5 == 0):
        print('Buzz');
        break;
      case (num % 3 == 0):
        print('Fizz');
        break;
      default:
        print(num);
    }
  }
}

Thank you in advanced.


Solution

  • num is a type of a built in type (common super type of int and double), also the case ...: expression needs to be constant and therefore can't be calculated based on non-constant values.

    I think using if is the best option.