Java 用于数据运算的高性能函数
我需要编写一个高性能函数,根据给定的datetime和timeshift计算新的datetime。它接受两个参数:Java 用于数据运算的高性能函数,java,datetime,Java,Datetime,我需要编写一个高性能函数,根据给定的datetime和timeshift计算新的datetime。它接受两个参数: 字符串,以YYYYMMDDHHmm格式表示日期 整数,以小时为单位表示时移 函数以第一个参数的格式返回字符串,该字符串是将timeshift应用于第一个参数的结果 预先知道,在程序生命周期中,第一个参数始终相同 我的实现包括以下步骤: 解析第一个参数以提取年、月、日期、小时、分钟 创建GregorianCalendar(年、月、日期、小时、分钟)对象 应用方法GregorianC
- 解析第一个参数以提取年、月、日期、小时、分钟
- 创建GregorianCalendar(年、月、日期、小时、分钟)对象
- 应用方法GregorianCalendar.add(小时、时移)
- 应用SimpleDataFormat将结果转换回字符串
fixedDate
timeShift
以小时为单位,然后Date shiftedDate=new Date(fixedDate.getTime()+(timeShift*3600000))
将是您计算的移位日期(请参阅和了解)shiftedDate
转换为字符串无限期重复第2步和第3步,
fixedDate
不会被修改,可以重复使用。如果第一个参数是一个不会经常更改的值,可以使用缓存:
static private Map<String,Calendar> dateCache = new HashMap<String,Calendar>();
并添加您的时间偏移值。如果可以,请使用该库,它使日期算法非常简单:
DateTime dt = new DateTime();
DateTime twoHoursLater = dt.plusHours(2);
它们有一个DateTimeFormatter
类,您可以使用该类将输入的日期时间字符串解析为DateTime
,例如:
DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyyMMddHHmm");
DateTime dt = fmt.parseDateTime(myDateString);
DateTime result = dt.plusHours(myTimeshiftInHours);
Joda Time也能与java.util.Date很好地互操作。我喜欢 我会尝试简单的回忆录:
// This is not thread safe. Either give each thread has its own
// (thread confined) converter object, or make the class threadsafe.
public class MyDateConverter {
private String lastDate;
private int lastShift;
private String lastResult;
public String shiftDate(String date, int shift) {
if (shift == lastShift && date.equals(lastDate)) {
return lastResult;
}
// Your existing code here
lastDate = date;
lastShift = shift
lastResult = result;
return result;
}
}
注意:如果
shift
和date
值很少更改,则此简单方法最为有效。如果其中一个频繁更改,则需要更复杂的缓存,代码将更复杂,开销(缓存未命中)将更高。如果您只是想避免重复第1步(可能还有第2步),请解析一次日期,然后保存获得的日期。然后,您可以在每次再次添加步骤之前(或者创建一个新的GregorianCalendar,如果重要的话,请测量它)。您需要同步缓存。。或者更好的按线程日历,以避免克隆如果缓存DateTime dt
(以及最后一个myDateString
值),并且仅当myDateString
变量与前一个变量不同时才创建一个新的日历,那么它只会在两个字符串上添加一个条件(成本很小)您将避免解析每次调用的第一个参数。@Yanick:如果度量结果显示缓存('memorization')是值得的,您可以通过映射将其扩展到许多值。当然,您也希望重用单个DateTimeFormatter,而不是在每次调用时重新创建它。
// This is not thread safe. Either give each thread has its own
// (thread confined) converter object, or make the class threadsafe.
public class MyDateConverter {
private String lastDate;
private int lastShift;
private String lastResult;
public String shiftDate(String date, int shift) {
if (shift == lastShift && date.equals(lastDate)) {
return lastResult;
}
// Your existing code here
lastDate = date;
lastShift = shift
lastResult = result;
return result;
}
}