Efficient way of looping an array of pointers

What is the most efficient way to loop through an array of pointers??

Example:

1
2
private:
  char * data;


then I have in a few places the following logic:

1
2
for (int i = 0; i < lengthOfArray; i++)
data[i] = str.data[i];


I'm just wondering if there is a more optimal way to loop through my array?

Thanks,
Last edited on
I'm just wondering if there is a more optimal way to loop through my array?

Not really.

I believe you're thinking of something like this:
1
2
3
char *src = str.data, *dest = data;
while (src < str.data + len)
    *dest++ = *src++;


You don't really know beforehand which way will be faster. But that kind of "optimisation" is not very useful and can be counterproductive. If you have a program that doesn't run fast enough you need to profile it to see where it is spending most of its time. That's where you can make the most difference.

So in general you should use whichever method makes the algorithm more clear.

Although, now that I think about it, if you just want to copy the data from one array to the other then memcpy is perhaps fastest.
 
memcpy(data, str.data, len);

Last edited on
Where do you allocate memory for that pointer?

How are you computing "lengthOfArray"?

Is data just an array of char or is it a C-string?


Topic archived. No new replies allowed.