user1509260
user1509260

Reputation: 3643

C++ optimization, using > instead of <=

Is it more expensive to check '<=' rather than '>' ?

The first one checks both < and ==, but '>' does just one check.

Or maybe the compiler optimizes this?

Upvotes: 2

Views: 258

Answers (5)

Andrew
Andrew

Reputation: 24846

For non built in types you can overload both operators as you wish:

class Foo
{
public:    
    bool operator<=(const Foo &other) const
    {

    }

    bool operator<(const Foo &other) const
    {

    }

};

So if comparison operators is the bottleneck of your application you are able to optimize your operators and <= can be calculated in different manner then calling < and ==

Upvotes: 3

eds
eds

Reputation: 439

No. <= is essentially the same as > with an extra NOT, and >= is the same as < with a NOT. (Which ones, if any, have an extra NOT I'm not sure but they are essentially all the same at the hardware level.)

Upvotes: 0

Moataz Elmasry
Moataz Elmasry

Reputation: 2519

No. both have the same cost. Assuming you are using a known standard compiler not a fancy one

Upvotes: 0

Alexey Frunze
Alexey Frunze

Reputation: 62058

There's rarely any noticeable difference. If you're thinking of this kind of optimizations, I bet, you're not optimizing the right thing.

Upvotes: 4

James Kanze
James Kanze

Reputation: 153919

It depends on what you're comparing, but for the build-in types, both are generally just one machine instruction.

Upvotes: 15

Related Questions