A Java bounds-checking optimization example -


i have read of jvms out there can optimize code execution removing bounds checking. trying figure out coding technique work better.

in method example1 below jvm ever figure out , eliminate bounds checking of source[index] reference?

is example2 better code practice? seem so, in algorithms inside loop index being out of bounds normal condition. don't want generating tons of exception objects inside loop.

public void example1(int [] source, int index) {     if (index >= 0 && index < source.length)         system.out.println("value " + source[index]);     else          system.out.println("out of range: " + index); }  public void example2(int [] source, int index) {     try {                 system.out.println("value " + source[index]);             } catch (indexoutofboundsexception exp) {         system.out.println("out of range: " + index);     } } 

these code fragments representational. aware in these examples bounds-checking hardly matter performance. working on embedded protocol application redundant bounds checking add up.

to first question, in example1 bounds check can theoretically eliminated. i'd expect best modern jit compilers (e.g. perhaps via common sub-expression elimination in bounds check when source[index] expanded). usual implementation dependent can't rely on it. otoh if bounds check isn't eliminated difference trivial - you're hitting cached memory location source.length , doing couple of integer compares overhead tiny.

example2 not practice - hitting exception catching , continuing if nothing happened. unless watching stdout closely might miss fact there bug in code.

there 2 common "good" possibilities depending on consider valid input "index":

  1. an out-of-bounds index value expected , considered valid input. in case should test , handle explicitly in example1. shouldn't need throw sort of exception in case.

  2. an out-of-bounds index unexpected (and therefore bug in calling code). code should raise exception here. if can catch , re-throw exception own message let indexoutofbounds exception propagate. don't worry performance impact of exception handling - have discovered bug , therefore want program fail , "loudly" can.....


Comments

Popular posts from this blog

c++ - Is it possible to compile a VST on linux? -

java - Output of Eclipse is rubbish -

jquery - Confused with JSON data and normal data in Django ajax request -