magicleon94
magicleon94

Reputation: 5172

Dart const as preprocessor directives

I was looking for something similar to preprocessor directives in Dart.

The idea is to avoid the compiling of certain portions of code conditionally to some flags.

Now, reading stuff like this I came to think that when the Dart compiler performs the Tree shaking it will throw away unused parts of code, excluding them from the compiled code.

Assuming I got this right, would something like this:

static const needExecute = false;

if (needExecute){
  //instructions
}

or like this:

static const needValue = false;

var myList = [
        "value1", 
        if(needValue) 
          "value2", 
        if(needValue) 
          "value3",
        ]

The compiler should know at compile time that that code will never be executed and it would fall "victim" of the tree shaking, not being compiled at all.

Moreover, would conditional imports be an acceptable way of doing things too?

I mean, could I use two different imports exposing a method which would be empty or contain the instructions (first case) or the two kinds of lists (second case).

Is there any way I can know this for sure, assuming I do not have the skills for decompiling an app?

Thanks a lot!

Upvotes: 4

Views: 1337

Answers (1)

Rémi Rousselet
Rémi Rousselet

Reputation: 277287

Your assumption is right. If the evaluation of an if can be evaluated at compile-time, it will be tree-shaked accordingly.

As such, writing:

const condition = true;

if (condition) {
  print('42');
} else {
  print('24');
}

will compile to:

print('42');

The if being removed because it was evaluated at compilation already. No need to re-evaluate it at runtime

Upvotes: 9

Related Questions