java - Why static/member variable are slower than local variable? -


I have seen this thread:

made your own class to check the speed

  public class questions {static long start; Static long time has passed; Static String Mastatic; Private string m public; Public static zero main (string [] args) {query q = new question (); Q.executeGlobal (); Q.executeStatic (); Q.executeLocal (); } Public Zero Execution Local () {string mLocal; StartTime = System.nanoTime (); For (Int i = 0; I <1000000000; i ++) {mLocal = ""; } ElapsedTime = System.nanoTime () - startTime; System.out.println ("local type:" + elapsedTime + "ns"); } Public executed globally () {startTime = System.nanoTime (); For {int i = 0; i <1000000000; i ++} {mPublic = ""; } ElapsedTime = System.nanoTime () - startTime; System.out.println ("Type Global:" + elapsedTime + "ns"); } Public Zero Execution Stable () {startTime = System.nanoTime (); For (int i = 0; i <1000000000; i ++) {mStatic = ""; } ElapsedTime = System.nanoTime () - startTime; System.out.println ("Type Static:" + + Appended Time "" NS ");}}  

Result:

  Type global: 45693028 ns Type Static: 43853723 NS Type Local: 2057505 ns  

found / putfield For getstatic / puttish is due to the bytecock, strong> Bytecode for member variables, it can be calculated through bit-transfer and some extra First of all I thought that only Object causes this, but the primitive result is the same local variables still

You are the victim of Runtime Optimization: -)

If you change your code a bit:

  question q = new question (); (Int i = 0; i & lt; 2; i ++) {q.executeGlobal (); Q.executeStatic (); Q.executeLocal (); }  

You get:

  type global: 38331 943 ns type static: 57761889 ns type local: 3010189 ns type global: 4624 9 688 ns Type Static: 52745009 ns type local: 0 ns  

What is going on very soon it shows that your local variables are being fixed, but never read (or use) ), And optimizes the entire loop.

For the difference between the class instance field and the Static field, they are both on the heap, but the static field is shared in all object instances, so there is an additional level of indirection


Comments

Popular posts from this blog

sqlite3 - UPDATE a table from the SELECT of another one -

c# - Showing a SelectedItem's Property -

javascript - Render HTML after each iteration in loop -