性能方面,每次调用给定数组的长度或将长度存储在变量中并每次调用该变量更好吗? [英] Performance wise, is it better to call the length of a given array every time or store the length in a variable and call that variable every time?
问题描述
我对一个给定阵列的长度进行了很多调用,我想知道是否更好地继续多次调用它(目前已经超过50次,但它会不断增长)或者将长度存储在一个中是否更好?整数并且每次都使用该整数。
I call on the length of a given array a lot and I was wondering if it is better to keep calling it numerous times (50+ times currently, but it keeps growing) or is it better to just store the length in an integer and use that integer every time.
如果我不清楚我在说什么,请考虑以下内容:
If I am unclear in what I am saying, consider the following:
我有一个String数组:
I have a String array:
String[] str = new String[500]; //The length is actually dynamic, not static
当然,我给它添加了一些值,但是我在整个申请过程中一直调用字符串的长度:
Of course, I put some values into it, but I call on the length of the string all the time throughout my application:
int a = str.length;
int b = str.length;
int c = str.length;
int d = str.length;
int e = str.length;
等等......所以最好这样做:(性能明智,不要非常关心内存)
and so on...so is it better to do this: (performance wise, don't care about memory as much)
int length = str.length;
int a = length;
int b = length;
int c = length;
int d = length;
int e = length;
谢谢。
推荐答案
没有区别。访问数组长度时不调用方法。你刚读了一个内部字段。即使您调用了一个方法,当前JVM的差异也可以忽略不计。
There is no difference. You don't call a method when accessing the length of the array. You just read an internal field. Even if you called a method, the difference would be negligible with current JVMs.
这篇关于性能方面,每次调用给定数组的长度或将长度存储在变量中并每次调用该变量更好吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!