Explain the internal workings of the Java Virtual Machine (JVM) and how garbage collection impacts performance.