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

  • 因某次更新造成线上处理数据性能降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分析,如有不对之处欢迎指正

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值