Different iterator and const_iterator (STL) performance

In Qt, there are similar classes for displaying a map. These classes provide the begin_const () method, which returns const_iterator. The documentation says that these constants should be used whenever possible because they are faster.

STL only provides const_iterator if the instance itself is const. Only one begin () method is executed (overloaded for const).

Is there any difference when reading elements with an iterator and const_iterator? (I don't know why there is a difference in Qt)

+6
source share
2 answers

The documentation says that these constants should be used whenever possible because they are faster.

Of course. From http://qt-project.org/doc/qt-4.8/containers.html#stl-style-iterators:

For each container class, there are two types of STL type iterators: one that provides read-only access, and one that provides read and write access. Read-only iterators should be used wherever possible because they are faster than read and write iterators.

What a stupid thing to say.

Safer? Yes. Faster? Even if that were the case (this is apparently not with gcc and clang), it is rarely preferable to use constant iterators over non-constant ones. This is premature optimization. The reason for the preference of constant iterators over non-constant is security. If you don’t need editable content, use a constant iterator. Think about what some programmer will do with your code.

As for begin compared to cbegin , this is a C ++ 11 add-on. This allows the auto keyword to use a constant iterator even in non-constant settings.

+5
source

The best reason to use const is to avoid errors and make the code more understandable.

It can be assumed that in some cases, the compiler could perform some optimizations that would not be possible with a non-constant iterator. An offset (when several variables and parameters can refer to the same object) is often an inhibitor of some optimizations. If the compiler can exclude certain forms of aliases, noticing that the constant constant can never change the value, perhaps this will allow some optimizations.

On the other hand, I would expect the compiler to be good enough to use a constant in such a way as to be able to achieve the same output with stream analysis.

+3
source

Source: https://habr.com/ru/post/914509/


All Articles