Speculators are people who specialise in bearing risks and do so for a price. Hiring these specialists reduces the risk for others. For it to make sense to both parties, the transfer must reduce the risk. The lowered risk could be due to the speculator’s more sophisticated risk assessment or their more considerable capital to ride out short-run losses. It could also be due to the variety of risks accepted.
An example would be a farmer selling their product in advance of growing it to a commodities speculator. In the case of a good season, they could have made a little more money by accepting the risk themselves. In a bad season, they have not had to bear the costs of having produced less. The farmer can focus on growing their crop without the concern that their income is unknown.
Gambling involves the creation of risk, while speculation minimises existing inherent risk. The economy as a whole benefits as the various speculators take on the risks. Areas in which speculators are unwilling to accept risk signals money is better off elsewhere.