Java Method invocation vs using a variable

前端 未结 14 2519
北海茫月
北海茫月 2020-11-27 02:57

Recently I got into a discussion with my Team lead about using temp variables vs calling getter methods. I was of the opinion for a long time that, if I know that I was goin

14条回答
  •  北荒
    北荒 (楼主)
    2020-11-27 03:10

    I've tested it in a very simple code :

    • created a class with a simple getter of an int (I tried both with final and non-final value for Num, didn't see any difference, mind that it's in the case num never change also...!):

      Num num = new Num(100_000_000);
      
    • compared 2 differents for loops:

      1: for(int i = 0; i < num.getNumber(); ++i){(...)}
      
      2: number = num.getNumber();
      for(int i = 0; i < number; ++i){(...)}
      

    The result were around 3 millis int the first one and around 2 millis in the second one. So there's a tiny difference, nothing to worry about for small loops, may be more problematic on big iterations or if you always call getter and need them a lot. For instance, in image processing if you want to be quick, don't use repetively getters I would advise...

提交回复
热议问题