Skip to content

Instantly share code, notes, and snippets.

@akostadinov
Last active May 10, 2021 04:26
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akostadinov/670a4dc93485128efb6023f5fa319521 to your computer and use it in GitHub Desktop.
Save akostadinov/670a4dc93485128efb6023f5fa319521 to your computer and use it in GitHub Desktop.
Benchmark Java Thread-Safe Time Formatter Implementations
@Grapes([
@Grab(group='org.gperfutils', module='gbench', version='[0.4,)'),
@Grab(group='org.apache.commons', module='commons-lang3', version='[3.7,)'),
@Grab(group='joda-time', module='joda-time', version='[2.9.9,)')
])
/**
* Java 8 DateTimeFormatter
*/
import java.util.Date;
import java.time.temporal.TemporalAccessor;
import java.time.Instant;
import java.time.ZonedDateTime;
// final TemporalAccessor tmpnow = Instant.now();
// final Date now = new Date(tmpnow.toEpochMilli());
final TemporalAccessor tmpnow = ZonedDateTime.now();
final Date now = new Date(Instant.from(tmpnow).toEpochMilli());
import java.time.format.DateTimeFormatter;
// dtfi = DateTimeFormatter.ISO_INSTANT;
dtfi = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ");
public String dtf(TemporalAccessor date) { dtfi.format(date); }
/**
* Java SimpleDateFormat
*/
import java.text.SimpleDateFormat;
// using clone seems to be twice faster than constructing
// public String sdf(Date date) { new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").format(date); }
sdti = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
public String sdf(Date date) { sdti.clone().format(date); }
/**
* Joda-Time
*/
import org.joda.time.DateTime;
// import org.joda.time.format.ISODateTimeFormat;
import org.joda.time.format.DateTimeFormat;
// DateTime jodanow = DateTime.now()
DateTime jodanow = new DateTime(now);
// jodadtfi = ISODateTimeFormat.dateTimeNoMillis();
jodadtfi = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ");
public String jodadtf(DateTime date) { date.toString(jodadtfi) }
/**
* Apache Commons Lang 3
*/
import org.apache.commons.lang3.time.FastDateFormat;
apachedtfi = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ssZ");
public String apachedtf(Date date) { apachedtfi.format(date) }
println "SimpleTimeFormat: ${sdf(now)}"
println "DateTimeFormatter: ${dtf(tmpnow)}"
println "JodaDateTimeFormatter: ${jodadtf(jodanow)}"
println "FastTimeFormatter: ${apachedtf(now)}"
r = benchmark {
"SimpleDateFormat" {
sdf(now)
}
"DateTimeFormatter" {
dtf(tmpnow)
}
"Joda-Time" {
jodadtf(jodanow)
}
"FastDateFormat" {
apachedtf(now)
}
"SimpleDateFormat_now" {
sdf(new Date())
}
"DateTimeFormatter_now" {
dtf(ZonedDateTime.now())
}
"Joda-Time_now" {
jodadtf(DateTime.now())
}
"FastDateFormat_now" {
apachedtf(new Date())
}
}
r.prettyPrint()
@tzachi81
Copy link

Hi Aleksandar, thanks for this post. Very helpful.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment