performance of comparing pointers with less than operator

Started by
3 comments, last by dmatter 14 years, 1 month ago
Is comparing pointers with "<" or ">" operators slow? Is it the same speed as comparing an integer? I'm working on a 32-bit machine. Would this be different on a 64-bit machine?
Advertisement
The time it takes to compare pointers is of the same order of the time it takes to compare integers, which is several orders of magnitude smaller than the time it takes to load a page of memory that is not cached, for example.

My point is that you should probably look for opportunities for optimization elsewhere (better algorithms, cache coherency, avoid branch misprediction...).
I'm not really trying to optimize. I just remember one time I was using a std::map with a custom key. The "<" operator on the key struct/class used a pointer to compare... then it was changed to compare using an int. I think we changed it because it was slower with the pointer. But it seems I'm mistaken, so I'll try the experiment again. Thanks for the reply.
The result of comparing pointers that don't point into the same object might be unspecified in the first place.

Quote:
--If two pointers p and q of the same type point to different objects
that are not members of the same object or elements of the same
array or to different functions, or if only one of them is null, the
results of p<q, p>q, p<=q, and p>=q are unspecified.


However, it should still be OK to use pointers as a key for a map (std::map<X*, Y>), because it should use the std::less<T> functor and

Quote:
8 For templates greater, less, greater_equal, and less_equal, the spe-
cializations for any pointer type yield a total order, even if the
built-in operators <, >, <=, >= do not.


But if you write your own comparison function, and compare unrelated pointers directly with relational operators, it might be a bit incorrect in the first place.

Not sure, though, may-be unspecified means here that there's no way of knowing if p < q or q < p, but as long as they define a consistent ordering, you should be OK?
Quote:Original post by visitor
Not sure, though, may-be unspecified means here that there's no way of knowing if p < q or q < p, but as long as they define a consistent ordering, you should be OK?
I'm going to say that 'unspecified results' here means that any ordering relation remains unspecified too. They haven't explicitly stated any ordering for the binary comparison operators on pointers so you probably shouldn't assume one. The functor templates, however, definitely define a total-order relation [smile]

This topic is closed to new replies.

Advertisement