Melatonin affects the sleep-wake cycle and is often better for sleep quality than magnesium. Magnesium may help you relax and fall asleep due to its effects on neurotransmitters and muscle relaxation.