The most common scenario for space-time swapping is caching, which allows different types of caching to be set to improve performance. Here is a small problem I have encountered. Problem Description
In the statistics of the historical income of the stock, it involves the operation of the trading day, such as getting a date to offset a certain number of days after the transaction. Since the trading day is a relatively fixed data, at the beginning of the system startup, it is loaded into the cache, stored in a ArrayList, and defines a method getdate (String from, int offset) to implement the offset value. The original code is as follows:
public string Getdatefast (string fromdate, int offset) {
if (Tradinglist.isempty ()) {
initialize ();
}
int index = Tradinglist.indexof (fromdate);
if (index = = 1) {return
null;
}
index-= offset;
Return Tradinglist.get (index);
}
The above code omits business details that are not related to technology.
In a business scenario, you need to call the method on more than 20,000 data, and print the following log:
It is not acceptable to see from the log that 20,000 of the data have cost more than 9 seconds. Problem Analysis
Because Tradinglist is stored with ArrayList, each indexof is required to do a full cycle, so indexof operation is the bottleneck of performance. Solving Method
There is a solution to the cause. The fastest lookup is O (1), and the storage structure that meets this condition is hashmap. So, in addition to storing the date sequence with ArrayList, in the initialization, the HashMap stores the index of the date. The code is as follows:
private void Initialize () {
tradinglist.clear ();
Dateindexmap.clear ();
Load the transaction's sequence from the database
tradinglist = Marketcalendardao.finddatebyistradingsortdatedesc (true);
Establishes the corresponding relationship for the date and position for
(int index = 0; index < tradinglist.size (); index + 1) {
dateindexmap.put ( index), index);
}
public string Getdatefast (string fromdate, int offset) {
if (Tradinglist.isempty ()) {
initialize ();
}
if (Dateindexmap.containskey (fromdate)) {
int index = Dateindexmap.get (fromdate);
index-= offset;
Return Tradinglist.get (index);
}
return null;
}
The final effect of the operation: