记一次简单的关于SimpleDateFormat的优化

# 有一个有趣的需求:java

(1)预先定义天天24小时不一样时间段的电价spa

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

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

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

## 方案1get

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), 结果很不理想io

## 方案2form

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左右class

相关文章
相关标签/搜索