Costco's membership fee (minimum is $60) has several benefits that the media don't like to talk about -- because it's unpleasant to mention it. The membership fee charged by Costco helps keep the riff-raff out. Although the cheapest Costco membership at $60/year looks like a trivial amount to middle-income people, even that tiny cost is enough to be an unreachable Mt Everest for the poorest segments of society. Therefore, the membership fee acts as a socially acceptable way to keep out the undesirables.
Often, you'll see a thread on reddit showing photos of "Walmart shoppers" with tube tops and loose pants with butt cracks showing. That's not the type of clientele that shops at Costco. Walmart also has a huge problem with shoplifting and employee theft (what the retail industry calls "shrinkage") and therefore, there's often a police car outside to arrest somebody. Costco's membership requirement is the hurdle that helps them avoid all that.
Costco makes money on the membership fees itself, but they also save money by not having to deal with shrinkage because their higher-income clientele has less problems.
The above advantages only adds to the other positives such as simpler logistics of ~4000 SKUs at Costco vs 40000 SKUs at Walmart.