0

Simple quesion but can't find the answer. I have a function

private Srting getStrOrNull(String str){
 if (str==null) return null;
 else{
  return "#"+str+"#";//ANY STRING MODIFICATION
 }
}

Can I modify this function in that way that not to use any if,switch clause? For example using hashmap etc.

I'll explain what for I need it. I have 1000s rows in database and for example to determine icon according to state for every row I do this way.

private HashMap<Int,String> iconPaths;

public String getIconPathByState(int id){
 return iconPaths.get(id)
}

I don't use any switches and ifs to do it as faster as possible as this function will be called 1000s times.

4
  • you want to add # as prefix and suffix to String ? I would suggest you to take both approach and measure performance difference Commented Dec 27, 2014 at 17:51
  • @Jigar Joshi - No, it's just for example. I edited. Commented Dec 27, 2014 at 17:52
  • 1
    if ANY STRING MODIFICATION is heavy and can save cycles by caching them in map then yes, if it is light then doesn't make huge difference, benchmark both Commented Dec 27, 2014 at 17:54
  • if you really want to improve your code - do not accept null as parameter and do not return null Commented Dec 27, 2014 at 18:10

3 Answers 3

3

The code "#"+str+"#" is going to take at least 100 times as long as the compare, so I think you are optimizing the wrong part here.

Sign up to request clarification or add additional context in comments.

2 Comments

Yes, refactoring to use a StringBuilder would be a lot faster.
Why wrong path. I just showed and example. In my example when I use hashmaps I have 12 icons. If I used switch with 12 cases...
3

This is premature optimization. Today's processors, like the i7, perform 100,000 millon instructions per second. 1000's of instructions is lost in the noise.

If you really think you need to speed it up, don't guess. Measure.

http://docs.oracle.com/javase/8/docs/technotes/guides/visualvm/index.html

Comments

2

Here is one approach which you can use sometimes, it will be slower in this artificial example with "#"+..., but main idea could be useful:

private final static String getStrOrNull(final String str) throws Exception {
    // first step prepare table for different states:
    // 0 - input value is null
    // 1 - input value is some not null string
    // in single thread application you can move this array out of the function as static variable to avoid memory allocation
    final Callable<String>[] func = new Callable[2];

    func[0] = new Callable<String>() {
        @Override
        public String call() {
            return null;
        }
    };

    func[1] = new Callable<String>() {
        @Override
        public String call() {
            return str.toLowerCase(); // any other string modification
        }
    };

    // now we need to convert our input variable into "state" (0 or 1)
    // to do this we're inserting string into set
    // if string is not null - it will be in map, final size will be 1
    // if string is null - we will remove it via remove(null), final size will be 0
    final Set<String> set = new HashSet<String>();
    set.add(str);
    set.remove(null);

    return func[set.size()].call();
}

here is another method how you can convert input variable into 0 or 1:

int i = System.identityHashCode(str); // returns 0 for null, non zero for all other values, you can also use unsafe getaddr
// converts 0 to 0, any non-zero value to 1:
int b = ((i >>> 16) & 0xffff) | (i & 0xffff);
b = ((b >>> 8) & 0xff) | (b & 0xff);
b = ((b >>> 4) & 0xf) | (b & 0xf);
b = ((b >>> 2) & 0x3) | (b & 0x3);
b = ((b >>> 1) & 0x1) | (b & 0x1);

return func[b].call();

6 Comments

Thank you very much. Interesting solution I didn't know about such way. You are the first who gave any solution to my question. Thank you!
Could you explain set.remove(null)?
@Lashane I know, I actually had not grasp what you were doing but now I get it.
@PashaTurok Lashane did not really present this as a solution to your particular problem but more like a general tactic. He did precise it would be slower than a comparison in your case
Thank you very much again. I will upvote your answer tomorrow as I'm out of upvote limit today.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.