Extract expression
In the process of software development, programmers can easily let the code do some "repetitive work" intentionally or unintentionally. In most cases, due to the computer's instructions to run , These "repeated efforts" do not pose a big threat to performance, but if the system performance is maximized, it is quite meaningful to extract these "repeated efforts".
Look at the following test case:
@Test public void test(){ long start = System.currentTimeMillis(); ArrayList list = new ArrayList(); for (int i = 0;i<100000;i++){ System.out.println(list.add(i)); } //以上是为了做准备 for (int i = 0;i<list.size();i++){ System.out.println(list.get(i)); } System.out.println(System.currentTimeMillis() - start);//5444 }
If we extract the list.size() method, the optimized code is as follows:
@Test public void test(){ long start = System.currentTimeMillis(); ArrayList list = new ArrayList(); for (int i = 0;i<100000;i++){ System.out.println(list.add(i)); } //以上是为了做准备 int n = list.size(); for (int i = 0;i<n;i++){ System.out.println(list.get(i)); } System.out.println(System.currentTimeMillis() - start);//3514 }
On my machine , the former takes 5444ms, and the latter takes 3514ms, a difference of about 2s. It can be seen that extracting repeated operations is quite meaningful.
The above is the detailed content of How to extract expression in java. For more information, please follow other related articles on the PHP Chinese website!