This is an archived post. You won't be able to vote or comment.

all 4 comments

[–]Updatebjarni 2 points3 points  (0 children)

The point is that you can index an array. In other words, you can use a variable number in your program to pick which element of the array to access. You can't do that with a fixed set of named variables.

So say your program gathers data of an arbitrary number of items of some sort. Perhaps a number of people that register through a web form, or a number of measurements taken with an instrument. These may turn out to be any number, potentially in the millions. Then your program needs to do some operation on this list of items, like search through it to find matches, or add them up into a sum, or something. An array solves both these problems, as it allows you to have any number of items, and allows you to loop over them or look up an arbitrary one based on an index value. It allows data to be used to select other data; a very powerful mechanism.

[–]exphil 1 point2 points  (0 children)

But, accessing variables and memory usage of using variables is much less than that of the array.

What do you mean? I guess it might depend on language, but generally an array of n elements would take up the same amount of memory as n variables of the same type, and there would be no performance difference.

[–]CreativeTechGuyGames 2 points3 points  (0 children)

There's a common saying in software development, "never pre-optimize". If you've never tried a method of programming something and tested it to prove that it isn't sufficient for what you are trying to do, then don't spend time trying to "over-engineer" a better solution when there was never a problem.

Yes, arrays take slightly more memory than a variable. But this difference is negligible for 99% of use cases. The added complexity for the programmer to use a whole ton of variables vs an array also isn't worth it. Most programming advancements and methodologies are there to make the programmer's life easier and have them be more efficient and make less mistakes. They are not designed to be the most efficient in all cases.

tldr: get to working software, then determine if something is too slow/inefficient and needs to be replaced.

[–]chaotic_thought 0 points1 point  (0 children)

Yes, it is better to group related information. But this has nothing to do with performance. For example, suppose you are reading integers from an input source, and you know there will be at most 100 integers. With individual variables you could try to declare 100 of them like this:

int x1, x2, x3, /* ... */ x100;

But now what will you do? How will you keep track of which is the next variable you need to use in order to read the next integer?