zoukankan      html  css  js  c++  java
  • 记一次简单的关于SimpleDateFormat的优化

    # 有一个有趣的需求:

    (1)预先定义每天24小时不同时间段的电价

    (2) 有一个list<map<timestamp,value>>: timestamp(时间戳);value(耗电量)

    (3) 求电价,也就是遍历list, 判断timestamp是哪个电价,然后相乘

    ## 有趣的地方在于怎么把timestamp转化为只有"HH:mm:ss"的格式(因为电价的定义只有这种格式)

    ## 方案1

    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.List;
    
    public class QQ {
    
        public static void main(String[] args) throws ParseException {
            Long ts = 1556606641000L;
            List<Long> list = new ArrayList<Long>();
            for (int i = 0; i < 200000; i++) {
                list.add(ts + i);
            }
    
            Long start = System.currentTimeMillis();
            for (Long e : list) {
                String str = timestampToStr(e, "HH:mm:ss");
                SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
                format.parse(str).getTime();
            }
            System.out.println(System.currentTimeMillis() - start);
        }
    
        private static String timestampToStr(Long timestamp, String formatStr) {
            SimpleDateFormat format = new SimpleDateFormat(formatStr);
            Date date = new Date(timestamp);
            return format.format(date);
        }
    }

    ## 上面的代码耗时 1s-1.5s之间(数据量为200000), 结果很不理想

    ## 方案2

    import java.text.ParseException;
    import java.util.ArrayList;
    import java.util.List;
    
    import org.joda.time.LocalTime;
    
    public class QQ {
    
        public static void main(String[] args) throws ParseException {
            Long ts = 1556606641000L;
            List<Long> list = new ArrayList<Long>();
            for (int i = 0; i < 200000; i++) {
                list.add(ts + i);
            }
    
            Long start = System.currentTimeMillis();
            for (Long e : list) {
                LocalTime time = new LocalTime(ts);
            }
            System.out.println(System.currentTimeMillis() - start);
        }
    
    }

    ## 耗时200-300ms左右

  • 相关阅读:
    antd Upload的使用
    table 的使用方法
    标题前点的制作
    插件multiBtnList的使用
    render的写法
    数据请求
    实体类为什么使用包装类
    el-table中如何遍历数组中对象里的数组?
    关于hash的描述,hashcode etc
    Java集合框架详解
  • 原文地址:https://www.cnblogs.com/lwmp/p/10797551.html
Copyright © 2011-2022 走看看