Compensators are a type of muzzle device that helps to reduce the recoil on your Glock. By reducing muzzle flip, they're helpful when rapidly shooting at targets.
When you shoot a Glock, gasses push the bullet out the barrel (the force of which causes muzzle flip). When the bullet exits the muzzle, a compensator vents these gasses up. The equal and opposite response pushes your muzzle down. The more ports, and also the larger the ports, the harder the gas pushes up, and pushes the pistol's muzzle down. Ports can also be added to the side to help mitigate against the horizontal recoil arc.
Compensators are useful when quickly firing, as you don't need nearly as much wait for the muzzle to "settle". Compensators are also good because aftermarket ones can't void Glock's warranty like other modifications can.