zoukankan      html  css  js  c++  java
  • 关于集合并集优化

      线上环境遇到跨库 事物的问题,历史数据 状态不一致问题。由于分布式事物还不成熟,决定使用手动写自动任务每天定时执行。大概思路是查询库1的数据,然后查询库2的数据,之后去差集后再更新数据2的数据。

          写完后,求差集 。刚开始使用了集合的removeAll ,测试环境数据量几千条没什么问题,但是考虑到线上有30多万条数据,于是写了个测试。发现使用removeAll超级慢。经过跟踪源码发现,removeAll里面使用了两次contains函数,相当是使用了笛卡尔积的方式 30万*30万。 于是决定优化。

         方式如下:

    long startTime = System.currentTimeMillis();
            LinkedList<String> result = new LinkedList<>();
    
    
            for (int i =0;i<300000;i++){
                result.add(i+"");
            }
    
            System.out.println("result size:" + result.size());
    
            List<String> list1 = new ArrayList<>();
            for (int j = 10;j<301000;j++){
                list1.add(j+"");
            }
    
            System.out.println("list1 size:" + list1.size());
    
            System.out.println("插入时间:" + (System.currentTimeMillis()-startTime));
    
            HashSet<String> hashSet = new HashSet<>(list1);
            Iterator<String> it = result.iterator();
    
            while (it.hasNext()){
                if (hashSet.contains(it.next())){
                    it.remove();
                }
            }
    
    
            System.out.println(result.size());
            for (String str : result){
                System.out.println("str:" + str);
            }
            long endTime = System.currentTimeMillis();
            long time = endTime-startTime;
            System.out.println("持续时间:" + time/1000 + "秒");

     这样基本是ms级的

  • 相关阅读:
    HDU1058Humble Numbers
    HDU1056 HangOver
    HDU1048The Hardest Problem Ever
    HDU 1028Ignatius and the Princess III(母函数简单题)
    HDU1014Uniform Generator
    HDU1013Digital Roots
    HDU1005Number Sequence(找规律)
    HDU1004 Let the Balloon Rise(map的简单用法)
    HDU1002 -A + B Problem II(大数a+b)
    Codeforces Round #363 (Div. 2)->C. Vacations
  • 原文地址:https://www.cnblogs.com/thinkingandworkinghard/p/9475879.html
Copyright © 2011-2022 走看看