Archived

This topic is now archived and is closed to further replies.

hpolloni

how faster is to use pointers

Recommended Posts

well,i know that returning a pointer in a function is faster than return the struct(or class) that it point to(i don''t know how to say this,my english sucks),but it make a real difference?, because i was watching some code,from an online tutorial,and they simple return the struct. that''s all folks

Share this post


Link to post
Share on other sites
The pointer can fit into a register. Returning something via a register is fast.

Most structs wont fit into a single register, so they have to be copied around memory. Memory is slow.

To answer you question, pointers are a hell of a lot faster.

Share this post


Link to post
Share on other sites
When your function returns a class/struct it makes yet another object in the memory which takes more memory, if its a pointer it doesnt make a new object, its also faster.



Share this post


Link to post
Share on other sites
Just to be another cook...

Often if you''re passing a structure or class into a function you should use a reference or pointer. If you''re not going to change the struct, use a const reference or const pointer.

For example, in C:


  
typedef struct
{
float x, y, z;
}
VECTOR3;

void MyFunction (const VECTOR3 * v)
{
printf ("%f, %f, %f\n", v->x, v->y, v->z);
}

VECTOR * BadFunction (void)
{
VECTOR3 v = {0, 1, 0};
return &v; // NEVER EVER DO THIS OR YOUR APP DIES

}


Note that the last function, BadFunction, returns a pointer to a local variable that no longer exists when the function returns. You can''t return structs by pointers like this. Instead you should do something like this:


  
void BetterFunction (VECTOR3 * v)
{
v->x = 0;
v->y = 1;
v->z = 0;
}


Hope this helps. Passing things by pointer or reference is a good way to avoid passing around huge chunks of data, and modifying data without making a copy.

In C++ you''d use references if you could. Change the "*" to "&" and the "->" to ".". A reference is like it sounds. It''s "another name" for a variable.

Hope this helps.


Helpful links:
How To Ask Questions The Smart Way | Google can help with your question | Search MSDN for help with standard C or Windows functions

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Just don''t return a pointer to a locally allocated object. An example is


Object* f()
{
Object a;

return &a;
}


What you should do is


Object* g()
{
Object* a = new Object();

return a;
}

Share this post


Link to post
Share on other sites