Memory vs Compute

struct Foo {
  int values[30];
  int cached_bar{0};

  int bar() {
    if (cached_bar == 0) {
      for (int i = 0; i < 30; ++i) {
        cached_bar += values[i] * i;
      }
    }

    return cached_bar;
  }
};

std::vector<Foo> arr(1'000'000);

for (auto &foo : arr) {
  Use(foo.bar());
}
struct Foo {
  int values[30];

  int bar() {
    int res{0};
    for (int i = 0; i < 30; ++i) {
      res += values[i] * i;
    }
    return res;
  }
};

std::vector<Foo> arr(1'000'000);

for (auto &foo : arr) {
  Use(foo.bar());
}

* The benchmark is run under Apple Macbook Air M2.

* For the full benchmark code, please refer here.