The problem of access speed between [][] and iterator(or pointer)

1
2
3
4
5
size_t A[10][10];
for(size_t i = 0; i < 10; ++i)
  for(size_t j = 0; j < 10; ++j)
    A[i][j] = i + j; //would compiler inteprete this to 
               //*(A + (i * 10) + j) = i + j? 


1
2
3
4
5
6
7
8
 size_t A[10][10];
 size_t* A_ptr = A[0];
 for(size_t i = 0; i < 10; ++i)
  for(size_t j = 0; j < 10; ++j)
  {
    *A_ptr = i + j;
    ++A_ptr;
  }


Someone say that the access speed of second example is faster, I don't know it is true or not
Thanks a lot
Last edited on
It all depends on the compiler, compilation options, and the target machine. However I would say that the second example will rather not be slower (on average).

Of course in practice it isn't really important as difference will be negligible, compared to for example effects of cache misses.
I am quite sure that on most compilers the second example will evaluate to exactly the same code as the first one, with the only difference being the majorly reduced readability. I MIGHT be wrong though.
This means I have to know how the compiler work if I wanted to generate clear and efficient codes?

The example two would be a little bit difficult to read
but the algorithm of stl(come from this forum) always write the code like the way of example two
Is this the price(generic vs readable) of generic programming have to pay for?(I hope not)
If so, maybe this is one of the reasons why many programmers would know OOP more than GP
Although GP is very powerful, but the coding way of GP may not very intuitive

Whatever, I am still like to learn the skill of GP
since STL do prove how useful GP could be

Last edited on
You are looking at this from the wrong side. Efficiency of a program depends mostly on its design and algorithms used. When your program is too slow, and you find the bottleneck, and you know that this bottleneck is CPU bound then (and only then) you should attempt to do low-level optimizations.

Doing these kind of optimizations everywhere is simply a waste of time as there won’t be any noticeable difference in efficiency of a program.

EDIT: By low-level optimizations I mean all attempts to change the generated machine instructions in order to save a few processor ticks.
Last edited on
I agree with you, Abramus
I should pay more times on the algorithm->data structure->architecture ot the program
before those minor optimization problems

What about generic programming?Do I have to deal with the coding way like example two?
Or there are another approaches to incorporate with generic programming?
Topic archived. No new replies allowed.