Memory efficient way to load large entity set for data export
Batches allow heavy processing to be spread out over several page
  requests, ensuring that the processing does not get interrupted
  because of a PHP timeout, while allowing the user to receive feedback
  on the progress of the ongoing operations. It also can reduce out of
  memory situations.
  
  Source: Example: Batch API 


You need to use the Batch API. There is no official docs for D8, but you can look at the batch_example module and the CSV Import module.

Good conceptual read, Drupal 8 Batch Processing but a bad code example.