线上 indexOf 引发的性能问题总结

米斯特程序猿 2021年04月22日 383次浏览
  • 因某次更新造成线上处理数据性能降2 ~ 3倍,没更新前处理时间在300毫秒左右,更新后为600 ~ 900毫秒
  • 经过代码排查,发现是因为增加如下代码
        boolean mainSiteIdCheck = data.indexOf("main_site_id") == -1;
        if (mainSiteIdCheck) {
            log.warn("缺少[main_site_id]", data);
            TotalUtil.dataErrorCount();
            return false;
        }
  • 由于indexOf 检索的字符串在中间部分,时间复杂度为O(N),所以包含该代码的方法执行时间增加了,最中造成线上处理性能下降,去掉后性能回归正常
  • indexOf 部分源码(JDK1.8)
static int indexOf(char[] source, int sourceOffset, int sourceCount,
            char[] target, int targetOffset, int targetCount,
            int fromIndex) {
        if (fromIndex >= sourceCount) {
            return (targetCount == 0 ? sourceCount : -1);
        }
        if (fromIndex < 0) {
            fromIndex = 0;
        }
        if (targetCount == 0) {
            return fromIndex;
        }

        char first = target[targetOffset];
        int max = sourceOffset + (sourceCount - targetCount);

        for (int i = sourceOffset + fromIndex; i <= max; i++) {
	      /* Look for first character. */
            /* 查找第一个字符,最好时间为O(1),最差时间为O(N),平均时间为O(N) */
            if (source[i] != first) {
                while (++i <= max && source[i] != first);
            }

             /* Found first character, now look at the rest of v2 */
            /* 找到第一个字符后,开始向后匹配字符 */
            if (i <= max) {
                int j = i + 1;
                int end = j + targetCount - 1;
                for (int k = targetOffset + 1; j < end && source[j]
                        == target[k]; j++, k++);

                if (j == end) {
		     /* Found whole string. */
                    /* 找到字符串,返回索引位置 */
                    return i - sourceOffset;
                }
            }
        }
        return -1;
    }

PS : 对于indexOf分析,如有不对之处欢迎指正