Performance Issue probably run out of Ram

Any further improvements?

Add comments.
Use Tools + Auto format to properly indent the code.
Delete the useless blank lines between closing }.