Versioned memory issues

Silverstripe Version: 4.13.44

Question: Why is so much memory used when saving images and how can i avoid this?

I’m currently using symbiote/silverstripe-queuedjobs for product imports and other things like that and i’m having issues with the memory used when i save an image, it’s going from like 36Mb to 600Mb+

I’ve debugged as much as i could, the memory increase happens right after using Versioned:

$contentLength = -1;
if ((int)$productPicture->attributes()->{'Size'}) {
    $contentLength = (int)$productPicture->attributes()->{'Size'};
}

$pathinfo = pathinfo((string)$productPicture->attributes()->{'Pic'});
$articleImage = ArticleImage::get()->filter(['ImageID' => $pathinfo['filename']])->first();
$assetObj = $articleImage ? $articleImage->File : Image::create();

if ($contentLength !== $articleImage->ContentLength) {
    $resizedImageObj = ImageResize::createFromString(file_get_contents((string)$productPicture->attributes()->{'Pic'}));

    if ($PicWidth > 1280) {
        $resizedImageObj->resizeToWidth(1280);
    }

    $assetObj->setFromString($resizedImageObj->getImageAsString(), 'icecat/' . $pathinfo['basename'], null, null, [
        'conflict' => AssetStore::CONFLICT_OVERWRITE,
        'visibility' => AssetStore::VISIBILITY_PUBLIC,
    ]);

    $resizedImageObj = null;
    unset($resizedImageObj);

    $this->addMessage(json_encode([
        'IsMain' => $IsMain,
        'Size' => $contentLength,
        'Pic' => (string)$productPicture->attributes()->{'Pic'},
        'Type' => (string)$productPicture->attributes()->{'Type'}
    ]));
}

Versioned::withVersionedMode(function () use ($assetObj) {
    Versioned::set_reading_mode('Stage.' . Versioned::DRAFT);
    $assetObj->write();
    $assetObj->publishSingle();
});

It takes about 30 seconds to finish write and publish:

[2025-01-27 00:00:14] updateProductGallery() {"IsMain":1,"Size":840203,"Pic":"https:\/\/inishop.com\/img\/gallery\/ffccb0c404d0ae97352dc64173c1dbc0dda0e5c5.jpg","Type":"ProductImage"} | memory: 26.38 MB  
[2025-01-27 00:00:14] updateProductGallery() beforeVersioned | memory: 26.38 MB  
[2025-01-27 00:00:47] updateProductGallery() afterVersioned | memory: 639.8 MB  

The problem is that i need to import/update several thousand products and those products can have 0 to 20 images and the job is most of the time waiting for memory release.

[2025-01-27 00:05:00] handleBatch() Job releasing memory and waiting (640.87 MB used) [] [] | memory: 640.87 MB  

I’d be gratefull for any advice.

Kind Regards