No system will optimally allocate resources. However projects are typically funded under competitive grants and that process is fairly good at moving slowly but methodically in the right direction.
Even when it doesn’t, it is training researchers who can enter systems which have different incentives like private research and development. That is a massive positive externality.