I'm currently testing out some webapp technologies in a java project and was wondering why the pages sometimes load fast and sometimes take almost 5s to load.
I finally found out that it is this line
LocalDateTime now = new LocalDateTime();
When it's called the first time, it takes forever to get the current time. When called after that, even somewhere completely different, it's pretty fast however.
I'm currently using
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>1.6.2</version>
</dependency>
Has anyone had any similar experience? Really stuck here.. I could use LocalDateTime some time early in my application to fasten up subsequent calls - but this seems pretty dull tho.
EDIT
I misuse Spring for that now:
@Service
public class JodaTimeLoader {
public JodaTimeLoader() {
LocalDateTime loadMe = new LocalDateTime();
}
}
The first time you do that, Joda Time loads a number of static resources (e.g., its chronology descriptors) which is the cost that you're seeing. This is a one-off cost; you pay it once per process. Load it early during startup if it really bothers you, perhaps like this:
static {
// Build the local caches inside Joda Time immediately instead of lazily
new LocalDateTime();
}
Joda-Time is designed for long running enterprise systems where a one-off up front load time is irrelevant compared to the faster performance during the rest of the application.
It takes about 77 ms on my system. That is quite long for a class.
Perhaps you just have to call it once on startup to make sure its already loaded.
If you want the current time quickly you can use System.currentTimeMillis(); which takes 0.0018 ms the first time I call it.
来源:https://stackoverflow.com/questions/6280829/jodatimes-localdatetime-is-slow-when-used-the-first-time