views:

83

answers:

4

I have a class which has a constructor that takes a const char*. It is:

c::c(const char* str) {
    a = 32;
    f = 0;
    data = new char[strlen(str)];
    memcpy(data, str, strlen(str));
}

And a function which takes one of them:

int foo(c& cinst);

You can call this function either by passing it an instance of a c:

c cinst("asdf");
foo(cinst);

or, because we have explicit initialization, you can do:

foo("asdf");

which will make a c by passing the constructor "asdf" and then pass the resulting object to foo.

However, this seems like it might be quite a bit less efficient than just overloading foo to take a const char*. Is it worth doing the overload for the speed or is the performance impact so small that it's a waste of space to make an overload? I'm trying to make my program as fast as possible, so speed is an important factor, so is size, but not so much.

+1  A: 

What will foo be doing with that const char*? If it's just going to make it own c object, then there's no point.

If it is going to use the char* directly (and the existing foo just pulled the char* out of the c object), then it would be better to write an overload.

James Curran
Exactly the answer I needed.
Thomas T.
A: 

It won't take zero time so it is one of the tradeoffs you have to take, speed versus api clarity. Of course it will depend on what you are doing in your function that takes a const char*, are you constructing a c object? In which case just offer the function with the c class interface.

DanDan
A: 

This sort of question is best answered with a profiler. Looking at the assembler code for it may also provide a clue.

EvilTeach
A: 

It's situational. It really depends on just how much is really going on inside a constructor in a given situation and how many times that code is actually being executed.

In the example you give, those are pretty trivial operations in that constructor. On any reasonable modern processor those operations are going to be very very quick. So unless that code is being executed a huge number of times per second or more, then I wouldn't even worry about it. (Of course the value of "huge" depends on what kind of machine you expect to run this on. For this constructor, on a typical desktop processor, I wouldn't even begin to worry until it gets up into the scale of at least hundreds-of-thousands of times per second.)

If this construction code does run some huge number of times, then you still ought to profile it and determine for sure if it's having a noticeable impact compared to everything else going on in your program. Optimization is a tricky thing. Sometimes what your gut feeling says is inefficient actually has little impact on the end results. Measurement is always to way to determine where you should actually be spending your time to most effectively make your program run faster.

TheUndeadFish