There are at least two ways inefficiency can creep into the market anyway.
First, markets may not be perfectly competitive or at equilibrium. Prices may not be determined by supply and demand, and outputs may deviate from the perfectly competitive norm.
Second, people may not pay for the goods, services, and resources they use. for example, in Equador, the loggers pollute water and thus destroy the businesses of the fish-farmers downstream. The loggers are using a resource they do not pay for -- fresh water -- and thus depriving the fish-farmers of it, even though (probably) the fish-farmers can make more effective use of it. In economics this sort of problem is called an "externality."
Finally, even if the perfectly competitive equilibrium is efficient, there may be other objectives besides efficiency. For example, efficiency can coexist with great inequality. A slave economy could be efficient. Most of us wouldn't want to adopt a slave system even so, I suspect.
We will explore the first two of those exceptions, noncompetitive markets and "externalities," in chapters to follow.
Nevertheless, the perfectly competitive economy stands as an ideal in which rational self-interest leads to an efficient allocation of resources -- a remarkable modern reflection of Adam Smith's founding insight.