Pointer / References & Performance

Pages: 12
Hey,

I know how to use pointer/references, but I'm still not sure when I should use them to get best performance for my c++ code.

I read through a lot of tutorials/books and the answer for using pointers is always different.

Overall, pointer should be faster, but I often read, if I don't know how to use pointers, I shouldn't use them.
At the moment I'm writing some small C++ OpenGL Games, so performance is very important to me, and not using pointers at all seems to be a wrong advice for me.

Can someone help me with examples where pointers/references could gain performance & be more efficient.
First, as a general rule, prefer references over pointers. Even if you have to use pointers, as in references aren't an option, then something like std::unique_ptr or std::shared_ptr would be better to use.

Now, the most common use case for pointers / references are to prevent copies. Here is an example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// an example world class
class World {
    public:
        // Functions, constructors, etc, etc, etc

    private:
        // a list of events in the current world - could be very large
        std::vector<Event> _evts;
};

// an unrelated function that needs access to the world, but doesn't modify
void doSomethingWithValue(World w) {
    // do something...
}

// the same function as above
void doSomethingWithReference(const World& w) {
    // do something...
}

In the above case, the second function will in general have a much better performance than the first one. This is because the first one requires you to copy the world, including that potentially massive list of objects. However, for the second one, all you need to copy is a small bit of data containing the address in memory of the object.

In general, for functions, anything other than the basic data types (e.g. int, char*, float, etc) should be passed by reference. However, apart from basic 'mindless' optimizations such as that which increase speed at no loss of productivity (a mere 6 letters more, including the optional const), try not to excessively optimize your code unless you have found a significant bottleneck.

On a fairly unrelated note, what version of OpenGL are you using? If you are using any version older than version 3.0, I would suggest starting to learn OpenGL again with a more recent tutorial (such as the one at arcsynthesis: www.arcsynthesis.org/gltut/ ). If you don't know, if you see anything in your program like glBegin, glVertex3f, and so on, you are probably using an old version of OpenGL. If you are so obsessed with performance, you'd definitely want to avoid the fixed pipeline of the older versions!
At the moment I'm reading a OpenGL Tutorial book from 2011 to stay up to date and i'm using VBO's instead of glBegin & ..

I think the main problem is, that I have a strong Java background.
I know how to code OOP and i also know pointers/references , C++ and so on.
But I still use Java-styled code in C++ like always create Objects(verctor,class) with 'new'
(Class c = new Class(); ) and i'm not sure if it's always necessary or good.
At the moment it works fine for me, but I think the bigger my projects get, the more impact my code will have on the performance.
Using a pointer vs. a reference makes no or very little impact on performance. Between calling void action(Object *o); or void action(Object &o);, none will speed up your program. The only thing that should make you decide between using a reference or a pointer in a given context is what you are planning to do with it. In the [passing a parameter to a function] context, using references merely makes it easier syntactically to access the object that you want to manipulate. But in a different context, references are not only a matter of preference; they are constant, and they can't be just initialized like a pointer.
1
2
3
int x=3;
int &ref;
ref=x;

This throws an error because ref is not initialized.
Plus, you can't have null references.
> But I still use Java-styled code in C++ like always create Objects(verctor,class) with 'new'
> (Class c = new Class(); ) and i'm not sure if it's always necessary or good.
It's unnecessary and awful.
Bjarne Stroustrup wrote:
Code that creates an object using new and then deletes it at the end of the same scope is ugly, error-prone, and inefficient.
another question:

example:

let's say i want to change a number in another function ( in C ):



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int num = 0;

int change1(int num)
{
    num = 1;
    return num;
}

void change2(int *num)
{
    *num = 2;
}

change1(num);
change2(&num);


what would be the faster and better way? 1 or 2
@ne555

I often got a problem with the stackoverflow exception,
so creating all objects without 'new' is also not really good ? hmm..
passing by explicit reference. which is neither 1 or 2.
(if you are passing anything but a simple datatype, so your example is slightly contrived)
Last edited on
Returning the value is almost certainly more efficient than pointer dereferencing, but it depends entirely on compiler optimizations and whether the function is inline(d).

You should always be more concerned about the 'right' way to do something rather than the 'most efficient' way to do something. Doing things the right way inherently leads to ore efficient code, whereas focusing on efficiency can cause you to lose sight of what's really going on.
@mutexe
passing by 'explicit' reference um mean like this?:

1
2
3
4
5
6
7
8
int num = 0;

int change(int &num)
{
  num = 10;
]

change(num);


im still not sure about implicit and explicit in c++



@LB

so the change1(int num) or getter / setter methods would be the right way?
> I often got a problem with the stackoverflow exception,
checkout your base case.
increase the stack size (ulimit)
design your really big objects with handlers. The handlers point to the big memory and take care of its destruction, you simply operate with an object.

> so the change1(int num) or getter / setter methods would be the right way?
`change1(int num)' does nothing, it has no effect.
getters and setters are evil http://www.javaworld.com/article/2073723/core-java/why-getter-and-setter-methods-are-evil.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int num = 0;

int change1(int num)
{
    num = 1;
    return num;
}

void change2(int *num)
{
    *num = 2;
}

change1(num);
change2(&num);

Note that these two functions do different things. To get the same effect you'd have to call them differently:
1
2
num = change1(num);
change2(num);

The performance difference between pointers and references will be minimal or nonexistent. References are usually implemented as pointers after all.

The only time when it's a good idea to local variable on the heap and delete it is when the variable will take up a LOT of space. In that case you don't want to overrun the stack space that you have. THis is particularly true with a multi-threaded program where each thread usually has a relatively small amount of stack space. It sounds like you're running into this limit, so look at the size of your objects and the size of the stack. Use your judgement to figure out what to change (size of the stack or where you allocate the storage).
somehow the new = got lost when i copied the src...

ok, so whenever its possible i should allocate my variables/class objects on the stack.

If the Objects is very large I should put it on the heap.
And I think when it should survive beyond its fuction it should be also be allocated on the heap.

And what about smartpointers for my objects ?
When it should survive beyond its function, you can return by value and take advantage of copy elision by using C++11 move semantics.
so allocation on the heap should only be done if the object needs a lot of space?
You should not be concerned about the size of objects like that. Compilers are smart enough to use the heap if they know an object will not fit on the stack. Also, if your object takes up so much space on the stack, you're doing it wrong.
ok as conclusion, I should prefer allocating a object on a stack over allocating it on the heap?
Last edited on
Yes.
> Compilers are smart enough to use the heap if they know an object will not fit on the stack.
┬┐are they?
Well, maybe I spoke a few years too soon. I am generally optimistic about compilers.
Pages: 12