C++ Logo

std-discussion

Advanced search

Re: Pointer comparison with operators vs function objects

From: Thiago Macieira <thiago_at_[hidden]>
Date: Mon, 15 Sep 2025 07:54:19 -0700
On Monday, 15 September 2025 06:59:34 Pacific Daylight Time Nate Eldredge via
Std-Discussion wrote:
> Cost. std::less may be more expensive than < , and the programmer should
> not have to pay that cost for the common case of comparing pointers within
> the same array.

There may be a higher cost to compile, but runtime the cost should be exactly
the same.

> The classic example was x86-16 with the "compact" or "large" code models, in
> which a data pointer is a "far" pointer consisting roughly of struct {
> unsigned offset; unsigned segment; };. (Here `unsigned` is 16 bits.) A
> 20-bit linear address is formed by (unsigned long)segment << 4 + offset.
>
> In these code models, every individual array exists within a single segment
> (and so is limited to 65535 bytes) but distinct arrays may be in different
> segments. So p1 < p2 can simply compare the offset parts, because the
> segments must agree if they point within the same array, which costs one
> cheap 16-bit compare instruction (cmp si, di). But std::less<T *>{}(p1,
> p2) must compute and compare the linear addresses, requiring several shifts
> and 32-bit adds, and being about an order of magnitude slower and larger.

Indeed, but in the medium and large memory models (__far function pointers),
you'd need to do the above anyway to compare function pointers, because you
couldn't be sure whether they were in the same segment or not. For example,
how do you order 0010:0108 vs 0200:0010 ?

Besides, std::less<T __far *> can be different from std::less<T __near *>.

-- 
Thiago Macieira - thiago (AT) macieira.info - thiago (AT) kde.org
  Principal Engineer - Intel Platform & System Engineering

Received on 2025-09-15 14:54:21