The title of this article comes from the knowledge planet. The background reply "knowledge planet" can participate in the Q & A.
The book continues to talk about this method of generating unique order numbers. This time, we will talk about performance problems.
Paste the original code first:
/** * Production unique transaction order number * * @return */ public static String createUniqueOrderNo() { SimpleDateFormat nyrsfm = new SimpleDateFormat("yyyyMMddHHmmss"); return nyrsfm.format(new Date()) + getRandomLengthCode(4); } /** * Get random SMS verification code * * @return */ public static String getRandomLengthCode(int length) { return String.valueOf((int) ((Math.random() * 9 + 1) * Math.pow(10, length - 1))); }
First, let's look at the first method. At first glance, we find a problem: this class is a tool class, and methods are static. In the first method, the SimpleDateFormat object is created every time it is called, and it is the same object, which wastes both memory and CPU. Generally speaking, it wastes time.
Amend to read:
static SimpleDateFormat nyrsfm = new SimpleDateFormat("yyyyMMddHHmmss"); /** * Production unique transaction order number * * @return */ public static String createUniqueOrderNo() { return nyrsfm.format(new Date()) + getRandomLengthCode(4); }
The test code is as follows:
public static void main(String[] args) { List<String> list = new ArrayList<>(); long nanoMark = getNanoMark(); range(10000).forEach(x -> { createUniqueOrderNo(); }); output(getFormatNumber(getNanoMark() - nanoMark)); }
This is the test result:
Obviously, the modified method is much faster.
Next, I'll study the method of obtaining time. I haven't found a good way yet, and I've ignored it for the time being. Let's take a look at the second method. To obtain the random four digits, first of all, there is another method to convert int into string, which is to use + connection directly. Here is the test code:
public static void main(String[] args) { List<String> list = new ArrayList<>(); long nanoMark = getNanoMark(); range(100000).forEach(x -> { // String ss = String.valueOf(1211); String ss = 1121 + ""; }); output(getFormatNumber(getNanoMark() - nanoMark)); }
This is the test result:
The difference is not very big. The + connection will create more objects and occupy more content resources. So it might be more appropriate to use the valueof() method. After some attempts, we found that the second method has nothing to optimize. Let's do that for the moment in terms of performance.
- Solemn statement: the article is forbidden to be reprinted or published by a third party (except Tencent cloud), and the original cause of the matter is Test nest, home page copy my seven original also pull black, your conscience won't hurt?