I know that "test it in your app" is a must. Nonetheless, I would like to ask for an analitical insight as well.
I have an in-app instruction queue (as an Array
) which elements are processed sequentially. The details are irrelevant. (Consider "instruction" as a virtual instruction, i.e. it is interpreted as such only in terms of my application -- like a small internal Virtual Machine).
The actual question is: which is faster for processing the queue elements -- virtual dispatch provided by Java, or a switch-case
?
In the first case, the
Array
consists of descendants of an ownOperation
object (or simply ofRunnable
-- you get the point). In this case, instruction execution is merely calling theOperation.run()
override of the object. Virtual dispatch will do the rest -- therun()
of the concrete instance will be called.The
Array
is a primitiveint
array, and each element is an instruction code that comes from a contiguous range (e.g. anint
between 0..65535). Instruction processing means that the instruction code is interpreted: (A) either via aswitch-case
statement, or (B) by using anArray
(ofOperation
objects) that is indexed directly by the instruction codes.
In the second case, I suppose switch-case
is optimized enough nowadays (especially because I'm using a contiguous range), so we can forget the Array
option.
To sum up, which is faster? Adding the interpreting code to the branches of the switch-case
, or using the virtual dispatch?
I suppose it breaks down to this: is a switch-case
faster or a virtual dispatch? I read that a switch-case
can be optimized to a branch table or jump instructions, and I guess in this case it will be possible.