简体   繁体   中英

What is the difference of these two java data structure?

The first version is:

int[] a = new int[1000];
int[] b = new int[1000];

The second version is:

class Helper{
    int a;
    int b;
}
Helper[] c = new Helper[1000];

My intuition tells me that the second one is better, but I could persuade myself in reason.... Can anyone compare the time complexity and space complexity of these two structure for me. For example, are these two version cost the same space? Or the second one cost less? Thank you!

The real question you should be asking is what is the relation between aa[i] and bb[i] . If aa[i] and bb[i] are properties of the same object (that has a more meaningful description than "Helper"), you should definitely put them in some class instead of using multiple primitive arrays. After all, Java is an object oriented language.

You shouldn't care about performance differences. Those will be insignificant. The important thing is that you code makes sense to whoever reads it.

While Eran is right, I'll add a few more points.

Sure, chances are you're very likely not going to bother about the performance - the difference is very insignificant for a general purpose application. Readability is what matters .

Still, in terms of technical details :

Space complexity is the same (it's always as many elements you have), but the absolute value in bytes is different.

Array of pairs will cost you more - each Java object has an overhead of several bytes. In case of two arrays, it's only a few bytes overhead per each array.

Also, in case of two arrays, the values of each array will reside next to each other in memory - reading all values of one of those array will be more effective in terms of CPU cache and memory layout. In case of array of objects, you now have an array of links to those objects and need first read the address of the object, before you can access the actual value of the field.

These are just general points so you can get a feeling of what's going on. In practice it all depends on how you want to work with those structures.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM