Sorting an .env file while preserving comments and empty lines

While trying to sort an .env file, I’m wondering what’s the most performant way of doing it while also preserving empty lines and (single or multiple) comments.

APP_URL=https://awesome-app.io
APP_NAME=testing
APP_ENV=prod
APP_KEY=
APP_DEBUG=
# this is a comment
# another comment
# third comment
PORT=

DB_CONNECTION=
DB_HOST=
DB_PORT=
DB_DATABASE=
DB_USERNAME=scott
DB_PASSWORD=tiger

test4="key#a23" # with comment
OTHER_ENV=

Ideally this should be sorted as this –

APP_DEBUG=
APP_ENV=prod
APP_KEY=
APP_NAME=testing
APP_URL=https://awesome-app.io

DB_CONNECTION=
DB_DATABASE=
DB_HOST=
DB_PASSWORD=tiger
DB_PORT=
DB_USERNAME=scott
LOG_CHANNEL=
OTHER_ENV=
# this is a comment
# another comment
# third comment
PORT=

test4="key#a23" # with comment