Java阵列效率 [英] Java Array Efficiency

查看:150
本文介绍了Java阵列效率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对这个机制并不是100%肯定所以我决定在这里发布以进一步澄清。

I am not 100% sure of the mechanism in action so I decided to post here for further clarifications.

我正在做一个应该处理大量的项目Java中的数据(必须是Java)。我希望它尽可能高效。有效率我的意思是内存和速度计算应首先出现,可读性应该排在第二位。

I am doing a project that should handle large amounts of data in Java (it has to be Java). I would like it to be as efficient as possible. By efficient I mean that memory and speed calculations should come in first and readability should come in second.

现在我有两种方法来存储我的数据:创建一个 MyObject

Now I have two ways to store my data: create one array of MyObject

1) MyObject[][] V = new MyObject[m][n]

或者创建两个int数组:

Or create two arrays of int:

2) int[][] V = new int[m][n]

3) int[][] P = new int[m][n]

显然 MyObject 包含至少两个字段和一些方法。现在我注意到,在循环遍历 MyObject 数组以分配值时,我必须调用 new ,否则我得到一个null指针异常。这意味着第1行中的 new 是不够的。这是一个比参数更昂贵的操作, P [i] [j] = n ,考虑到数组也是Java中的对象?

Clearly MyObject contains at least two fields and some methods. Now I notice that while looping over the MyObject array to assign values I have to call new or else I get a null pointer exception. This means that the new in line 1 didn't suffice. Is this a more expensive operation than, for sake of argument, P[i][j]=n, considering that arrays are also objects in Java?

推荐答案



这是一个比为了论证更昂贵的操作,P [i ] [j] = n,考虑到数组也是Java中的对象?

Is this a more expensive operation than, for sake of argument, P[i][j]=n, considering that arrays are also objects in Java?


在第一个case创建一个数组对象,用于存储array类型的其他对象。数组对象和要存储在数组中的对象都需要实例化,这意味着您将需要 m * n + 1 对象实例化以及(m * n + 1)* objectSize 内存消耗。

In the first case you create an array object which is to store other objects of type array. Both the array object and the objects that are to be stored in the array need to be instantiated meaning that you will need m * n + 1 object instantiations and also (m * n + 1) * objectSize memory consumption.

在第二种情况下,你只需要实例化数组对象; int原语不是对象,所以这应该更快,也更高效,因为对象内存大小是int的几倍。这里你基本上有1个对象实例化和(m * n)* intSize + objectSize 内存消耗。

In the second case you only have to instantiate the array object; int primitives are not objects so this should me more faster and also more memory efficient since and Object memory size is several times larger than that of an int. Here you basically have 1 object instantiation and (m * n) * intSize + objectSize memory consumption.

使用原语的另一个原因是,当用作局部变量时,它们会保留在堆栈中;在将计算值存储在数组中之前,您可能会在方法中使用中间局部变量,并且这些变量的内存的分配/释放时间比生活在堆上的对象的分配/释放时间高几倍。

Another reason for using primitives is the fact that when used as local variables they are kept on the stack; you will probably use intermediate local variables inside a method before storing the computed value in the array and the allocation/deallocation time for the memory of these variables is several times higher than that of an object which lives on the heap.

这篇关于Java阵列效率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆