Java for循环每次都通过list.size()和 string.length()获取大小性能

有人说在for循环之前用一个局部变量先获取到list.size()、str.length(),然后在for循环的判断条件里通过这个局部变量替换list.size()、str.length()会节省数据计算的时间。事实真的是这样吗?下面就为大家解答这个问题。

说明:此文章针对Android SDK 进行说明。

List.size()

首先我们看一下List接口,我们知道.size()方法是List接口的一个方法,返回一个int类型的值。

复制代码
public interface List<E> extends Collection<E> {
    //省略部分代码...
    
    /**
     * Returns the number of elements in this {@code List}.
     *
     * @return the number of elements in this {@code List}.
     */
    public int size();
    
    //省略部分代码...
}

接口中的方法都是没有具体实现的,我们下面看一下List的实现类ArrayList(LinkList也一样,这里讲ArrayList)。我们先看下ArrayList类中的size()方法是如何实现的:

复制代码
public class ArrayList<E> extends AbstractList<E> implements Cloneable, Serializable, RandomAccess {

    //省略部分代码...
    /**
     * Returns the number of elements in this {@code ArrayList}.
     *
     * @return the number of elements in this {@code ArrayList}.
     */
    @Override public int size() {
        return size;
    }
    //省略部分代码...
}

我们看到ArrayList里的size()方法直接return了一个size,通过查看发现size是ArrayList类中的一个int类型的成员变量,代表list结合中的元素数量。

复制代码
    /**
     * The number of elements in this list.
     */
    int size;

通过跟踪size变量发现在ArrayList类中的add,remove方法中都会动态改变size的大小。

复制代码
 /**
     * Adds the specified object at the end of this {@code ArrayList}.
     *
     * @param object
     *            the object to add.
     * @return always true
     */
    @Override public boolean add(E object) {
        Object[] a = array;
        int s = size;
        if (s == a.length) {
            Object[] newArray = new Object[s +
                    (s < (MIN_CAPACITY_INCREMENT / 2) ?
                     MIN_CAPACITY_INCREMENT : s >> 1)];
            System.arraycopy(a, 0, newArray, 0, s);
            array = a = newArray;
        }
        a[s] = object;
        size = s + 1; // 添加元素size增加
        modCount++;
        return true;
    }
...
    /**
     * Removes the object at the specified location from this list.
     *
     * @param index
     *            the index of the object to remove.
     * @return the removed object.
     * @throws IndexOutOfBoundsException
     *             when {@code location < 0 || location >= size()}
     */
    @Override public E remove(int index) {
        Object[] a = array;
        int s = size;
        if (index >= s) {
            throwIndexOutOfBoundsException(index, s);
        }
        @SuppressWarnings("unchecked") E result = (E) a[index];
        System.arraycopy(a, index + 1, a, index, --s - index); //删除元素 size--
        a[s] = null;  // Prevent memory leak
        size = s;
        modCount++;
        return result;
    }

通过上述代码我们知道通过ArrayList中的.size()方法获取集合长度,会直接返回一个集合元素数量的变量值,而不会每次调用size()方法都重新计算下集合的元素数量再返回。下面我们在看下String.length()。

String.Length()

我们看下java.lang包下得String类,首先找到String类中的.length()方法:

复制代码
/**
 * An immutable sequence of UTF-16 {@code char}s.
 * See {@link Character} for details about the relationship between {@code char} and
 * Unicode code points.
 *
 * @see StringBuffer
 * @see StringBuilder
 * @see Charset
 * @since 1.0
 */
public final class String implements Serializable, Comparable<String>, CharSequence {
    //省略部分代码...
    
     private final int count;

    //省略部分代码...
    
    /**
     * Returns the number of {@code char}s in this string. If this string contains surrogate pairs,
     * this is not the same as the number of code points.
     */
    public int length() {
        return count;
    }
    
    //省略部分代码...
}

我们发现跟ArrayList中的size()方法一样,返回了一个int类型的成员变量count。这个count是怎么赋值的我也不清楚,有兴趣的可以去研究一下。

#总结

综上所述,我们就可以知道List.size()和String.length()方法都是直接返回一个int类型变量值,而不会花费时间再去计算大小后返回,所以放心的去使用size()和length()方法吧。

相关推荐
ChinaRainbowSea3 小时前
MySQL 索引的数据结构(详细说明)
java·数据结构·数据库·后端·mysql
白晨并不是很能熬夜4 小时前
【JVM】字节码指令集
java·开发语言·汇编·jvm·数据结构·后端·javac
*.✧屠苏隐遥(ノ◕ヮ◕)ノ*.✧4 小时前
C语言_数据结构总结7:顺序队列(循环队列)
c语言·开发语言·数据结构·算法·visualstudio·visual studio
橘颂TA4 小时前
每日一练之合并两个有序链表
数据结构·链表
LIUJH12334 小时前
数据结构——单调栈
开发语言·数据结构·c++·算法
爱宇阳5 小时前
如何在 Windows 10 启用卓越性能模式及不同电源计划对比
windows·卓越模式·电池选项
shylyly_5 小时前
list的模拟实现
数据结构·c++·链表·迭代器·list·list的模拟实现
ianozo6 小时前
数据结构--【栈与队列】笔记
数据结构·笔记
Tomorrow'sThinker6 小时前
Python零基础学习第三天:函数与数据结构
开发语言·windows·python
路飞雪吖~6 小时前
数据结构 && 常见的排序算法
数据结构·算法·排序算法