Home > Java > javaTutorial > body text

How to extract expression in java

WBOY
Release: 2023-05-24 14:31:06
forward
744 people have browsed it

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     }
Copy after login

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    }
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template