In general modern optimizing compiler can do pretty powerful optimizations. It is very rarely worth it to do such optimizations yourself, usually you will just be getting in the compilers way. Before you even look at optimizing code you should profile your code to determine were the performance issue are.
A quick test with godbolt (see live code) using this code:
void function() {
std::set<int> set ;
set.insert( 10 ) ;
set.insert( 20 ) ;
for(int i = 0; i < set.size(); i++)
{
printf( "%d\n", i ) ;
}
}
Shows that it is directly accessing the count variable and not making a function call, the relevant assembly is:
movq $0, 56(%rsp) #, MEM[(struct _Rb_tree_impl *)&set]._M_node_count
and:
cmpq %rbx, 56(%rsp) # ivtmp.115, MEM[(long unsigned int *)&set + 40B]
So it would seem at least in this simple case the gcc
optimizer was able to do the quick trick you wanted to do yourself. Although the generated code is different clang
seems to be doing something similar as well.
Update
The question was updated to mention Visual Studio.
I don't know of an online tool to generate the Visual Studio assembly otherwise I would check that as well but I would not be surprised if Visual Studio also performs a similar optimization. As we can see the optimization is definitely possible. Once you generate the assembly in Visual Studio it is matter of determining whether a call to size()
is made every iteration of the loop or not.