Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficiency of std::get with std::tuple

Tags:

c++

c++11

I'm curious as to the lookup time that a call to std::get<> on a std::tuple<> takes. Some brief googling (including the reference pages which usually have this information) turned up no results.

My initial intuition (and fear) is that the recursive structure of tuple (if it is implemented as a variadic template) would lead to get requiring an order of N lookups (A call to get<3>(t) looking like t.rest().rest().first(). I'm hoping I'm way off here...

Then again, I would hope the compiler would be able to optimize this to directly return the correct offset without the overhead of N of calls.

Basically what I want: is there a specced guarantee on runtime? does this restrict how std::tuple is implemented?

like image 544
Anthony Sottile Avatar asked Apr 23 '13 12:04

Anthony Sottile


People also ask

Is STD tuple slow?

It is fully expected that std::tuple will be slower than std::pair when not optimized, because it is more complicated object. A pair has exactly two members, so its methods are straightforward to define. But tuple has arbitrary number of members and the only way to iterate over template argument list is with recursion.

What is std :: tuple?

Class template std::tuple is a fixed-size collection of heterogeneous values. It is a generalization of std::pair.


2 Answers

The efficiency will be comparable to accessing a member of a struct. The get<> is resolved at compile time.

like image 61
David Rodríguez - dribeas Avatar answered Oct 13 '22 09:10

David Rodríguez - dribeas


The C++ specification does not provide a guarantee on the runtime performance of any function. Even when it states asymptotic requirements, that only guarantees the relative number of operations, not the performance of those operations. O(1) doesn't mean fast, nor does O(n) mean slow.

You can either trust your compiler/optimizer/standard library implementation, or you can rewrite it all yourself to get whatever performance you want. std::get, under most reasonable compilers (with optimizations on), should perform more or less equivalently to directly accessing the value from a struct. But the spec doesn't require that at any point.

like image 24
Nicol Bolas Avatar answered Oct 13 '22 08:10

Nicol Bolas