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;