3

I'm working on a generic library class for a collage assignment, and it is very important that the code runs as efficient as possible, that is if we can reduce an if-statement we should do it.

I have the following code which is needed to initialize an array if it is a fundamental type such as double or int.

T b[dim];
if(std::is_fundemental::<T>::value) 
{ 
    memset(b, 0, dim*sizeof(T));
}

Now the question is whether this check is optimized out, such that it does not make a runtime check, or do i need to create a template for the initialization with a specialization for fundamental types?

I use G++ with C++11, but it should be able to run without the check on most, preferably all, compilers.

4

3 回答 3

6

The standard doesn't address optimization, but I can't imagine a compiler which wouldn't do this optimization. But does it really matter: you're talking about at most one or two machine instructions, after which you call a function which does a lot more. And formally speaking, doesn't work except for integral types. (Not that I've ever heard of a machine where a double with all 0 bits wasn't 0.0.)

But FWIW: std::uninitialized_fill_n should be at least as fast, and you don't need the if, since it will work with all types.

于 2013-05-15T11:27:55.343 回答
4

Compile it with the asm listing enabled and take a look what compiler did in each case. The only way to know for sure what will happen.

P.S. Different compilers might produce different results. But I guess you already know that.

于 2013-05-15T11:27:15.123 回答
3

If you use compile time constants to enable code or not, you can also use specialised template functions and use SFINAE to enable the tamplate or not.This guarantee that only the needed functionality is compiled/linked in. This feature is independent from optimisation.

The following example give you an idea:

#include <iostream>
#include <type_traits>

using namespace std;


template <typename T>
void Do( T t, typename std::enable_if<std::is_integral<T>::value >::type* = 0)
{
    cout << "Is fundamental" << endl;
}

template <typename T>
void Do( T t, typename std::enable_if<std::is_integral<T>::value == false>::type* = 0)
{
    cout << "Is not fundamental" << endl;
}

class NonFuncdamental
{} nonFundamental;

int fundamental;

int main()
{
    Do( fundamental );
    Do( nonFundamental );
    return 0;
}
于 2013-05-15T11:30:37.473 回答