r/cpp_questions • • 7d ago

SOLVED Performance of std::vector

In the university we had to implement quicksort, the unsigned ints are stored in std::vector. I have accidentally discovered, that all algorithms, despite how students implemented them, are much faster when instead of directly accessing data from the vector like that:

arr[n]

we write:

unsigned int *a = arr.data()

and access that data by writing:

a[n]

But I can't understand why is that, in both cases it translates to one and the same: *(a + n)

The code is compiled on Clion IDE if that changes anything, no custom settings for compilation are used.

I can't directly share the algorithms for copyright reasons as they are not mine.

34 Upvotes

63 comments sorted by

View all comments

2

u/WikiBox 7d ago

I would assume that there are range checks for vector[n]. That can significantly slow down access. You should be able to examine the code generated and/or the library, and figure it out.

4

u/Flimsy_Complaint490 7d ago

[] has no bound checks.

at() does bound checking.

6

u/didntplaymysummercar 7d ago

at() is guaranteed to throw if you're out of bounds.

[] on some standard library implementations will bounds check in debug or if you opt into it. MSVC does it out of the box in debug: "Expression: vector subscript out of range"

1

u/Normal-Narwhal0xFF 7d ago

That's true in the standard but debug builds could add vendor-specific range checks, just like optional "checked iterators". Since debug builds are for catching bugs ...

1

u/imradzi 4d ago

vectors [] don't do range check. It just explode. To do range check use at() function.

1

u/UndefFox 7d ago edited 7d ago

It doesn't do any bound checking:

      /**
       *    Subscript access to the data contained in the %vector.
       *   __n The index of the element for which data should be
       *  accessed.
       *  u/return  Read/write reference to data.
       *
       *  This operator allows for easy, array-style, data access.
       *  Note that data access with this operator is unchecked and
       *  out_of_range lookups are not defined. (For checked lookups
       *  see at().)
       */
      _GLIBCXX_NODISCARD _GLIBCXX20_CONSTEXPR
      reference
      operator[](size_type __n) _GLIBCXX_NOEXCEPT
      {
__glibcxx_requires_subscript(__n);
return *(this->_M_impl._M_start + __n);
      }

Most likely either the call isn't inlined, or the pointer is constantly being loaded over and over if they didn't pass vector as const/

edit: it does check on debug builds:

# define __glibcxx_requires_subscript(_N)\
  __glibcxx_assert(_N < this->size())

2

u/oriolid 7d ago

This is nitpicking, but that depends on the compiler. Access outside bounds is UB so it's completely legal to check the bounds and crash the app if the check fails. This is from AppleClang:

  [[__nodiscard__]] _LIBCPP_CONSTEXPR_SINCE_CXX20 _LIBCPP_HIDE_FROM_ABI reference operator[](size_type __n) _NOEXCEPT {
    _LIBCPP_ASSERT_VALID_ELEMENT_ACCESS(__n < size(), "vector[] index out of bounds");
    return this->__begin_[__n];
  }
  [[__nodiscard__]] _LIBCPP_CONSTEXPR_SINCE_CXX20 _LIBCPP_HIDE_FROM_ABI const_reference
  operator[](size_type __n) const _NOEXCEPT {
    _LIBCPP_ASSERT_VALID_ELEMENT_ACCESS(__n < size(), "vector[] index out of bounds");
    return this->__begin_[__n];
  }

The assert is disabled by default. If I was writing a programming assignment checker, I would enable it.

1

u/serafean 7d ago

Invalid access through [], compiled without optimizations, gcc-16:

/usr/lib/gcc/x86_64-pc-linux-gnu/16/include/g++-v16/bits/stl_vector.h:1253: constexpr std::vector<_Tp, _Alloc>::reference std::vector<_Tp, _Alloc>::operator[](size_type) [with _Tp = int; _Alloc = std::allocator<int>; reference = int&; size_type = long unsigned int]: Assertion '__n < this->size()' failed.

-O1 already disables this assert.

1

u/UndefFox 7d ago

Yeah, didn't think to check the defines...:

# define __glibcxx_requires_subscript(_N)\
  __glibcxx_assert(_N < this->size())

So yeah, it does check on debug build.