4

Repeated Function Calls vs Storage Results in Temporary Variables

 2 years ago
source link: https://www.codesd.com/item/repeated-function-calls-vs-storage-results-in-temporary-variables.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Repeated Function Calls vs Storage Results in Temporary Variables

advertisements

My code looked like:

class Main {
    public static void main(String args[]){
         String[] s1 = {"This ", "is ", "a ","sentence ", "."};
         String sentence = Arrays.toString(s1);
         System.out.println(sentence.substring(4, sentence.length()-1));
    }

    private static <T> String arrayToString(T[] t){
         StringBuilder sb = new StringBuilder();
         for(T val: t){
            sb.append(val.toString());
         }
    }
}

I tried to do the above in a single line as:

System.out.println(arrayToString(s1).substring(
                                       4, arrayToString(s1).length()));

My question is that I have called the arrayToString() method multiple times inorder to avoid storing a reference to the computed value.

  1. Will the arrayToString computation be carried out multiple times?
  2. Is there some mechanism in Java that reduces the penalty for these multiple calls?
  3. Am I better off using the previous version of the code?

In general, when coding in Java, you should recognize that your code is just-in-time compiled when it is executed more often. Since the calculations of

arrayToString(s1).substring(4, arrayToString(s1).length())

are rather predictable, you can expect that once the just-in-time compiler kicks in, the performance penalty should be resolved as it will create a cache for your calculations by itself. This is of course a too optimistic assumption for any code to be optimized but with Java, it is normally best to stick to writing readable code and not to worry too much about performance, this gap between code abstraction and performance is partly bridged away by the Java virtual machine.

In general, you can monitor performance of compiled code using a tool such as for example JIT watch which I can only recommend. It is difficult to pinpoint performance bottlenecks sometimes but from my experience, code like yours will never result in a bad user experience as it is merely the processing of a simple string what takes a few clock cycles, this would not even suffice to ping a database. Just while you are reading this text, my phone could probably have done the calculations billions of times.

To conclude, people worry about performance too much. Writing maintainable and readable code should always be your primary target.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK