Are optimizers moving temporary non-POD types from loops?

Given the following code:

while(is_running) { std::vector<buffer> buffers; // fill buffers // use buffers } 

Do modern compilers perform the following conversions?

 std::vector<bufer> buffers; while(is_running) { // fill buffers // use buffers buffers.clear(); } 
+6
source share
2 answers

The only way to know for sure is to check, but I would be very surprised if the optimizer performed this optimization.

To even begin this optimization, the compiler had to either: 1) know enough about the internal functions involved in the "implementation" (for example) that operator new and operator delete are basically mirror images or another, or 2) it would have to generate all code for all built-in functions (up to calls to operator new and operator delete and have sufficient intelligence to be able to derive the same output from the code.

I can hardly imagine the first, but I don’t remember ever being seen. Given the complexities of a typical heap manager, the second amazes me as incredibly incredible.

Bottom line: I was surprised before, and I'm sure I will again, but it will be a big surprise than most.

+4
source

I would be surprised to see that the compiler really knows the std containers and calls their methods without my explicit request. If that were the case, imagine how the compiler logic should be augmented whenever a new library module is released!

It would be interesting, however, to find out that some C ++ compilers have some knowledge of the standard library.

EDIT: Well, I found an example of this knowledge: for loops based on C ++ 11 ranges, std :: begin and std :: end are used for ranges.

In any case, we programmers must really understand what we are writing and find out ways to optimize it. The compiler should simply translate our instructions, applying only small (but significant) optimizations (for example, embedding, copying, etc.).

0
source

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


All Articles