Mohit Sehgal
Mohit Sehgal

Reputation: 865

Using Pointers in C++ decreases runtime?

I have a simple question that whether only using pointers instead of normal variables increase the efficiency of the program either time wise or memory wise? For an instance if I use following program to swap two integers.

#include<iostream>
#include<conio.h>
#include<new>
using namespace std;
int main()
{
   int *a=new int;
   int *b=new int;
   int *c=new int;
   cin>>(*a)>>(*b);
   *c=*a;*a=*b;*b=*c;
   cout<<"swapping";
   cout<<*a<<*b;
getch();
}

Upvotes: 1

Views: 702

Answers (4)

Mike Dunlavey
Mike Dunlavey

Reputation: 40699

This code does almost nothing at the level where you wrote it. If you step through it at the instruction level, you will see that each call to new executes 100s of instructions, and the cout << calls do even far more.

That's what you're measuring.

Upvotes: 0

kevintodisco
kevintodisco

Reputation: 5191

The only thing I can think of that might make using a pointer slower than using a local variable is that the generated assembly might involve more complex memory addressing, thus resulting in larger machine op-codes, which in turn would take ever-so-slightly more time to execute.

That time difference would be so negligible though that you shouldn't worry about it.

What you should consider is that allocation on the stack is much faster than allocation on the heap. In other words:

int* a = new int;

is slower than:

int a;

but only because of the allocation new int, not because you are using a pointer.

Upvotes: 3

Alex
Alex

Reputation: 7858

In the example given above, it is less efficient both time wise and memory wise.

  • Dynamic allocation cost more time than local variables (there are function calls and work to be done, local variables are created by substracting from a stack pointer, often just one operation for all local variables).
  • Dynamic allocation cost more memory than local variables (there are supporting data structures in the memory manager).

Pointers can make the program more efficient when they are used to prevent copying large structures. ints don't fall in this category.

Upvotes: 4

Keith Randall
Keith Randall

Reputation: 23265

Using pointers to variables instead of variables is unlikely to improve performance. Write the code in clearest way possible and let the compiler optimize the code for you. If anything, using pointers is likely to slow things down as it makes the compiler analysis harder.

For large objects, it is worth keeping pointers to objects instead of copying those objects around. Maybe that is the kernel of truth from which you are incorrectly extrapolating.

Upvotes: 9

Related Questions