My guess is that masturbating or being with your girlfriend helps to calm or relax before you fall asleep. I've noticed that I tend to have the worst dreams when I'm stressed out or in a bad mood.
“This planet has - or rather had - a problem, which was this: most of the people living on it were unhappy for pretty much of the time. Many solutions were suggested for this problem, but most of these were largely concerned with the movement of small green pieces of paper, which was odd because on the whole it wasn't the small green pieces of paper that were unhappy.” ― Douglas Adams, The Hitchhiker's Guide to the Galaxy