I have made a function in the the build in python console in QGIS (pyQGIS), which (among others) performs a raster calculation. I want to use my function to loop through multiple rasters. However, I run into a memory issue when doing so. I have found the sinner to be the raster calculator, where the memory is not cleared after processing the raster calculation (calc.processCalculation()). I have tried various solutions including; loading and removing the resulting layer with *removeMapLayer*, saving the output to a file (instead of using the memory) and using *del* combined with *gc.collect()*. But the memory is still not cleared, which ultimately causes the memory to fill up when running the function several times. Does anybody know how to free the memory after running the raster calculatior in PyQGIS? I have tested the code using QGIS 3.24.4, 3.28.2, and 3.22.12. The relevant part of my code looks like this, where Rasterfile1 and 2 are inputs to the function (full paths to raster files): lyr1 = QgsRasterLayer(Rasterfile1) lyr2 = QgsRasterLayer(Rasterfile2) entries = [] ras = QgsRasterCalculatorEntry() ras.ref = 'ras@1' ras.raster = lyr1 ras.bandNumber = 1 entries.append(ras) ras = QgsRasterCalculatorEntry() ras.ref = 'ras@2' ras.raster = lyr2 ras.bandNumber = 1 entries.append(ras) lyr2.extent(), lyr2.width(), lyr2.height(), entries) QgsRasterCalculator('if(ras@1 - ras@2>0,ras@1 - ras@2,0)', "memory", 'GTiff', lyr2.extent(), lyr2.width(), lyr2.height(), entries) calc = QgsRasterCalculator('if(ras@1 - ras@2>0,ras@1 - ras@2,0)', "memory", 'GTiff', calc.processCalculation() result=iface.addRasterLayer("memory",'resultingRaster')