Easy solution is using Magento 2 CLI and adding memory limit inside command.
For Compilation:
php -dmemory_limit=3G bin/magento setup:di:compile
For Content Deployment:
php -dmemory_limit=3G bin/magento setup:static-content:deploy
You can change to more value if your problem is not resolved.
where 3G = 3 GigaBytes
You can also set memory_limit in your php.ini file then you don’t need to define every time in the command.
memory_limit = 3G