Java – local or instance members

The following code proves that method1 is faster than method2 Anyone can comment on the reasons for this behavior

class Trial {
        String _member;
        void method1() {
            for(int i=0;i<30480;i++) {
                _member += "test";
            }
        }
        void method2() {
            String temp="";
            for(int i=0;i<30480;i++) {
                temp += "test";
            }
            _member = temp;
        }

        public static void main(String args[]) {
            Trial t = new Trial();
            long startTime1 = System.currentTimeMillis();
            t.method1();
            long endTime1 = System.currentTimeMillis();
            long startTime2 = System.currentTimeMillis();
            t.method2();
            long endTime2 = System.currentTimeMillis();
            System.out.println(endTime1 - startTime1);
            System.out.println(endTime2 - startTime2);
        }
    }

Solution

No, it doesn't prove that

It depends on many factors When I run this code, I get

1403
1248

So in my environment, your code "proves" that method1 is slower than method2

During benchmarking, you need to pay attention to cache and JVM preheating

You can also have a look

> How do I write a correct micro-benchmark in Java? > Avoid jvm warmup

For more information

I refactor the main method slightly:

...

static void doBenchmark() {
   Trial t = new Trial();

   long startTime1 = System.currentTimeMillis();
   t.method1();
   long endTime1 = System.currentTimeMillis();

   long startTime2 = System.currentTimeMillis();
   t.method2();
   long endTime2 = System.currentTimeMillis();

   System.out.println(endTime1 - startTime1);
   System.out.println(endTime2 - startTime2);
}

public static void main(String args[]) {

   for (int i = 0;  i < 20;  i++) {
      doBenchmark();
      System.out.println("----");
   }
}

This results in the first iteration of the for loop having similar values, but then the results converge and are no longer significantly different:

1396
1133
----
1052
1070
----
688
711
----
728
726
----
715
709
----
...

Even, sometimes method 1 seems to be faster, sometimes method 2 - this is most likely due to inaccurate measurements

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>