smttsp
smttsp

Reputation: 4191

Speed comparison of two code

I believe there are many similar questions, sorry if this is too common. I want to learn which one is better/faster/space efficient etc and why.

public static void(String[] main){
    //case 1
    String[] str_arr = new String[n];
    method1(str_arr)

    //case 2
    String[] str_arr = new String[n];
    String[] arr = new String[n];
    for(int i=0; i < n; i++){
        arr[i] = str_arr[i].split("some_char")[2];
    }
    method2(arr);
}

void method1(String[] str_arr){
    String[] arr = new String[n];
    for(int i=0; i < n; i++){
        arr[i] = str_arr[i].split("aChar")[2];//assume there are 50 of aChar 
    }
//  do_something with arr ;
}

void method2(String[] arr){
//  do_something with arr ;
}

Which one should I prefer?

Thanks in advance.

Upvotes: 0

Views: 72

Answers (1)

Jitsu
Jitsu

Reputation: 769

This is purely up to your discretion.

When it comes to performance reasons:

  • Use enhanced for loops, where you can, as they can sometimes impact the loop performance (see a nice micro-benchmark here: Java Enhanced-For-Loop FASTER than traditional?), or...
  • Do not create additional storage array if you do not need the originals anymore. Simply read the value, split() it and store it back. On very large arrays, you'll save yourself some allocation time and space.
  • In this particular example, the actual cost of method invocation is neglible. If you're extra paranoid (not recommended) you could make the method static to prevent being it thiscall function.

In terms of clean and tidy code:

  • Your method looks like it may be something generic so it's a great candidate for just a method that takes an array, along with the delimiter, and splits all its elements.
  • main() code is by convenience advised to be as small and compact as possible.

TL;DR Go for the first option, and eventually make some modification.

Also, it may be a good idea to split the elements before actually putting them inside the array.

Upvotes: 1

Related Questions