You don't actually defrag memory, you defrag a hard drive.
When you turn the computer off, it empties the memory of anything held within it, because that data can only be held whilst there is electricity in the machine.
Going back to the hard drive, it depends upon how much use the machine gets, as to how often a defrag is necessary. My machine is in constant use and I tend to defrag every three or four months.
How is it done? Go into Windows Explorer and Right Click on the drive you wish to defrag, select Properties; Tools; and the defrag option. Avoid shutting the machine down during the operation, and try and make sure all applications are closed and I would advise you do not use the machine whilst this is going on. That way, you will get the most efficient defrag. If you wish to be ultra fussy, you can do it from Safe Mode, but it's not normally necessary except if you have a problem.
What's it all about. When files are saved to a drive, they are not automatically saved in one place and can be spread all over the drive. This causes delays when the drive is required to read those files going from place to place to find the fragments. Defrag, as the name suggests, reorganizes the files and puts them all in one place, theoretically speeding up your machine.