PALEN
PALEN

Reputation: 2876

Fastest way to copy an array - Does it have something questionable?

When working with arrays of the same length, consider creating a structure which only contains an array so that it is easier to copy the array by simply copying the structure into another one.

The definition and declaration of the structure would be like this:

typedef struct {
    char array[X]; /* X is an arbitrary constant */
} Array;

Array array1;

Then, perform the copy by simply doing:

Array array2;
array2 = array1;

I have found that this as the fastest way of copying an array. Does it have any disadvantage?

Edit: X is an arbitrary constant, let's say 10. The array is not a variable length array.

Upvotes: 2

Views: 2735

Answers (3)

Wilbur Vandrsmith
Wilbur Vandrsmith

Reputation: 5050

This works fine, but since X must be defined at compile-time it is rather inflexible. You can get the same performance over an array of any length by using memcpy instead. In fact, compilers will usually translate array2 = array1 into a call to memcpy.


As mentioned in the comments, whether direct assignment gets translated into a memcpy call depends on the size of the array amongst other compiler heuristics.

Upvotes: 1

johnnycrash
johnnycrash

Reputation: 5344

It's entirely dependent on the compiler and level of optimizations you use. The compiler "should" reduce it to memcpy with a constant size, which should in turn be reduced to whatever machine specific operations exist for copying various size blocks of memory. Small blocks should be highly machine specific these days. Actually calling the memcpy library function to copy 4 bytes would be so "10 years ago."

With optimizations off all performance bets are off.

Upvotes: 1

eq-
eq-

Reputation: 10096

X may be arbitrary (up until the limits of your compile environment), but it's (naturally) the same number for all objects of type Array. If you need many arrays of same length and type to be copied to each other, there's nothing inherently wrong about this, although accessing these arrays might be more cumbersome than usual.

Array array1;
array1.array[0] // to access the first element

Upvotes: 2

Related Questions