3

In our flutter project, with use a lot of enums and extensions. Some of us write switch statements, some others use maps. I was wondering what practice is considered the best one in terms of time, memory etc ?

enum Animal { cat, dog, bird }

Switch statement:

extension AnimalExtension on Animal {
    String get name {
        switch (this) {
            case Animal.cat:
                return 'Cat';
            case Animal.dog:
                return 'Dog';
            case Animal.bird:
                return 'Bird';
        }
    }
}

Map:

extension AnimalExtension on Animal {
    String get name => {
        Animal.cat: 'Cat',
        Animal.dog: 'Dog',
        Animal.bird: 'Bird',
    }[this];
}

Also, for the map method, is it better to create a static const Map instead of instantiating it on the fly at every call?

Valentin Vignal
  • 6,151
  • 2
  • 33
  • 73

1 Answers1

3

I wouldn't worry about speed for something this small, not unless it's at the heart of the inner loop of your computation.

The switch has the chance to be more time efficient, the map will likely have less code (it reuses the Map.[] code). The map should definitely be const.

If you want to optimize performance and code size, I'd go with:

  String get name => const ['cat', 'dog', 'bird'][this.index];
jamesdlin
  • 81,374
  • 13
  • 159
  • 204
lrn
  • 64,680
  • 7
  • 105
  • 121