Home > Mobile >  for-loop with variable vs without using a variable
for-loop with variable vs without using a variable

Time:08-26

Typically, when iterating through a list of objects, for example in a for...in loop, the object is assigned to a variable first.

Builder(
  builder: (context) {
    final List<KeyValue> keyValue = [
      KeyValue(
        key: 'Name',
        value: data.name,
      ),
      KeyValue(
        key: 'Age',
        value: data.age,
      ),
      KeyValue(
        key: 'Gender',
        value: data.gender,
      ),
    ];

    return Column(
      children: [
        for (var item in keyValue)
          Padding(
            padding: EdgeInsets.all(8),
            child: Text('${item.key} : ${item.value}'),
          ),
      ],
    );
  },
),

But what if I placed the list directly inside the loop to save the trouble of creating a variable?

Builder(
  builder: (context) {
    return Column(
      children: [
        for (var item in [
          KeyValue(
            key: 'Name',
            value: data.name,
          ),
          KeyValue(
            key: 'Age',
            value: data.age,
          ),
          KeyValue(
            key: 'Gender',
            value: data.gender,
          ),
        ])
          Padding(
            padding: EdgeInsets.all(8),
            child: Text('${item.key} : ${item.value}'),
          ),
      ],
    );
  },
),

Is this anti-pattern? Or does the former have any performance significance over the latter? Because if I'm not mistaken, in Javascript, assigning a value to a constant variable may prevent it from being recreated as a new instance. Can someone enlighten me on this?

CodePudding user response:

This method is less readable, and it won't buy you anything performance wise (it's quite likely that the compiler would produce the machine code equivalent of your second snippet in either case).

In either case, since the value cannot be made a constant (due to the reference to data [unless data is itself a constant]), the majority of the runtime cost (which is still tiny) is in constructing the value itself, not in assigning it to a named variable.

For that reason, it's better to go with the more readable version.

  • Related