Is using an arraylist of Tuple(double,int,int) slower than two arraylists

17,532

Solution 1

Your question is missing context. This problem has been asked many times, and there is no single best solution.

In my opinion, the best way to model the data is to have a logical type that represents your data. (You are currently using a tuple, but it would be better to have a specific type with methods.)

So, I would do the following:

List<NumberContainer> list = new ArrayList<NumberContainer>();

As far as speed goes in particular - It depends on how you are going to use the data. If you are looking for fast access times, it may be best to use a map and key each item on some value.

Solution 2

Unless you've written a custom Tuple class which maintain an unboxed double and two int values, they'll be boxed anyway... so basically you'll end up with the extra Tuple object per item, although just one underlying array and ArrayList instead of 3.

If the triple of values represents a meaningful composite value though, I'd be very tempted to write a small class to encapsulate the three of them with meaningful names for each property. That way you're likely to end up with more readable code and efficient code (as there won't be any boxing).

Solution 3

Most likely using an array of objects (or in your case, tuples) which would save you a line of code, and put everything in one place (the tuple.)

Here's the sample code for what I would do.

//Class
class container() {
    int value1, value2;
    double value3;
    //Constructor
    container(int value1, int value2, double value3) {
        this.value1 = value1;
        this.value2 = value2;
        this.value3 = value3;
    }
}

//Implementation
ArrayList<container> arr=new ArrayList<container>();
Share:
17,532
Wei Shi
Author by

Wei Shi

@Test public void me(){ assertEquals(me,PEOPLE.Programmer); }

Updated on June 04, 2022

Comments

  • Wei Shi
    Wei Shi almost 2 years

    Is using an arraylist of Tuple(double,int,int) slower than three separate arraylists? I want to avoid creating lots of Tuple objects, but does method 2 create objects by autoboxing?

    //Method 1
    Arraylist<Tuple> arr=new Arraylist<Tuple>();
    Tuple t=new Tuple(double, int, int);
    class Tuple{
    
        private double value;
        private int a;
        private int b;
    }
    
    //Method 2
    Arraylist<Double> arr=new Arraylist<Double>();
    Arraylist<Integer> arr=new Arraylist<Integer>();
    Arraylist<Integer> arr=new Arraylist<Integer>();
    
  • jjnguy
    jjnguy almost 13 years
    @Kal, what do you mean by 'possible XY problem'
  • Kal
    Kal almost 13 years
    meta.stackexchange.com/questions/66377/what-is-the-xy-proble‌​m @jjnguy -- I was referring to your comment about the question missing context. Its likely the OP's problem is different.