Reputation: 21978
I have a main
method looks like this.
struct list *l = array_list();
if (l == NULL) {
return EXIT_FAILURE;
}
srand(time(NULL));
int size = 4;
for (int i = 0; i < size; i++) {
int *d = malloc(sizeof(int));
*d = rand();
list_insert_last(l, d);
printf("inserted: %d\n", *d);
}
printf("size: %zu\n", list_size(l));
for (int i = 0; i < size; i++) {
int *d = list_delete_first(l);
printf("deleted: %d\n", *d);
free(d);
}
printf("size: %zu\n", list_size(l));
array_list_free(l);
return EXIT_SUCCESS;
My question is, even though I already tagged premature-optimization
, about the int *d
variable.
Will it be better declaring the variable once out of loops and reuse it?
struct list *l = array_list();
if (l == NULL) {
return EXIT_FAILURE;
}
srand(time(NULL));
int size = 4;
int *d; // declare once
for (int i = 0; i < size; i++) {
d = malloc(sizeof(int)); // reuse it
*d = rand();
list_insert_last(l, d);
printf("inserted: %d\n", *d);
}
printf("size: %zu\n", list_size(l));
for (int i = 0; i < size; i++) {
d = list_delete_first(l); // reuse it
printf("deleted: %d\n", *d);
free(d);
}
printf("size: %zu\n", list_size(l));
array_list_free(l);
return EXIT_SUCCESS;
Upvotes: 1
Views: 217
Reputation: 213720
It doesn't make any difference. The place of a variable declaration in C code is not often the same place as the place of allocation in the machine code. So this is indeed "pre-mature optimization".
When I disassemble your code I get identical machine code for d = malloc
and int* d = malloc
. Depending on size
, the compiler might even unroll the whole loop during optimization. In either case, d
is likely to be allocated in a CPU index register, which is as fast as allocation can be. (Some 2-3 cycles or whatever depending on ISA.)
It is however generally good practice to reduce scope of variables as much as possible, to make the code more readable and to reduce namespace clutter. Therefore the local int *d = malloc
is the correct form. (And as a bonus, C90 compatible as well.)
Now, in case you actually care about performance, the major bottleneck in this code is the I/O with printf
, which is astronomically slower than allocating a single int
variable.
Similarly, repeated calls to malloc
in a loop is astronomically slower. It also causes needless heap fragmentation and blocks efficient data cache use, since the allocated memory is all over the place.
The rand() calls may be somewhat slow too, depending on the C lib implementation.
Upvotes: 1
Reputation: 336
I think any modern compiler will involve a static single assignment representation at some point, and so it will not make a difference in the generated code.
I prefer your first example but that is 100% for the benefit of human readers who will not have to wonder if d
is used later. The compiler will do enough analysis to know that they are equivalent.
Upvotes: 1