My shop page was very slow when I had over 100 products, REALLY slow. So I had to investigate what happened. So here are some points.

Find default variation

One thing I did for every product was to find the default variation to show correct image, and the code I used was this. My products have 15 variations, and this was really bad for performance.

$default_attributes = $product->get_default_attributes();
$available_variations = $product->get_available_variations();

foreach($available_variations as $variation_values ) {
  $found_variations = 0;
  foreach($default_attributes as $key => $default_attribute_value ) {
                
    if ($variation_values['attributes']['attribute_'.$key] == $default_attribute_value) {
      $found_variations++;
    }
  }
  // return variation_id if found all of the default variations 
  if (count($default_attributes) == $found_variations) {
    return $variation_values['variation_id'];
  }
}

Instead i found the neat little function find_matching_product_variation, so instead of the nested foreach loops, I use the Data_Store_CPT to do the same.

$default_attributes = $product->get_default_attributes();
$attributes = [];
foreach ($default_attributes as $key => $value) {
  $attributes['attribute_'.$key] = $value;
}
return (new \WC_Product_Data_Store_CPT())->find_matching_product_variation(
        new \WC_Product($product->get_id()),
        $attributes
);

The same procedure that on my machine in the first foreach loops took 70-90 ms now take around 2 ms instead!