为什么String方法regionMatches不委托给重载方法

时间:2018-11-27 05:45:29

标签: java java-8

boolean regionMatches(int toffset, String other, int ooffset, int len) is implemented as中的方法java.lang.String

public boolean regionMatches(int toffset, String other, int ooffset, 
        int len) { 
    char ta[] = value; 
    int to = toffset; 
    char pa[] = other.value; 
    int po = ooffset; 
    // Note: toffset, ooffset, or len might be near -1>>>1. 
    if ((ooffset < 0) || (toffset < 0) 
            || (toffset > (long)value.length - len) 
            || (ooffset > (long)other.value.length - len)) { 
        return false; 
    } 
    while (len-- > 0) { 
        if (ta[to++] != pa[po++]) { 
            return false; 
        } 
    } 
    return true; 
}

由于有一个覆盖了相同功能的重载方法,为什么这种方法不能像简单委托那样实现

public boolean regionMatches(int toffset, String other, int ooffset, int len) {
    return regionMatches(false, toffset, other, ooffset, len);
}

1 个答案:

答案 0 :(得分:2)

首先,这是一个与实现有关的选择,因此实际上可能会在您建议的委派下遇到替代实现。这就是为什么重要的是指定您要指的是哪种实现。

Oracle’s JDK or OpenJDK(这似乎是您所指的Java 8实现)的情况下,很可能是出于性能方面的考虑而做出此决定。如您所见,当两个字符不匹配时,使用regionMatches参数的boolean ignoreCase的实现将在循环内重新检查此参数。

这可能是实现这两种操作的起点,但在某些情况下却成为性能瓶颈。通常,决定编写特殊的实现而不是更一般地处理操作的决定是基于对广泛的现实生活应用程序进行概要分析的。

区分大小写匹配的专用regionMatches实现由字符数组上非常短的直接循环组成,这可能会对HotSpot优化器的效率产生巨大影响。例如。可能会将此循环编译为本机代码,一次比较多个字符。

较新的JDK必须修改代码,因为自Java 9以来,使用byte[]数组而不是char[]数组,并且其中可能包含iso-latin-1或utf-16编码的数据,因此必须处理不同的情况。实施者借此机会介绍了委托though it is the other way round

public boolean regionMatches(boolean ignoreCase, int toffset,
        String other, int ooffset, int len) {
    if (!ignoreCase) {
        return regionMatches(toffset, other, ooffset, len);
    }
// specialized case insensitive comparison follows

因此,现在,无论您是在没有使用regionMatches参数还是使用boolean的情况下调用false的情况下,都获得了优化的区分大小写的比较。此外,不区分大小写的匹配操作也得到了优化,因为不会boolean参数被循环检查。