开发者

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

Is using an arraylist of Tuple(double,int,int) slower than three separate arraylists? I want to avoid creating lots of Tuple objects, bu开发者_如何学Pythont 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>();


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.


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).


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>();


If Tople is a class with 3 ivars, in that case that would be the way to go.

Aditionaly arralist only take objects so it will autobox all the primitives, but if you are using a class it will definitly not autobox the ivars in the class.


To answer your direct question, method2 does create objects by autoboxing assuming that the values you're putting in are primitives (double, int, etc.). Of course, if you use a Tuple class, you're also creating objects, but you will be creating 1/3 the number of objects, assuming the Tuple class maintains two ints and a double.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜