Java Reference
InDepth Information
Interestingly, the reverse is not necessarily true: C code that calls back into Java does not suf
fer a large performance penalty (depending on the parameters involved). For example, con
sider the following code:
public
public
void
void
main
() {
calculateError
();
}
public
public
void
void
calculateError
() {
for
for
(
int
int
i
=
0
;
i
<
numberOfTrials
;
i
++) {
error
+=
50

calc
(
numberOfIterations
);
}
}
public
public
double
double
calc
(
int
int
n
) {
double
double
sum
=
0
;
for
for
(
int
int
i
=
0
;
i
<
n
;
i
++) {
int
int
r
=
random
(
100
);
// Return random value between 1 and 100
sum
+=
r
;
}
return
return
sum
/
n
;
}
This (completely nonsensical) code has two main loops: the inner loop makes multiple calls
to code that generates a random number, and the outer loop repeatedly calls that inner loop to
see how close to the expected value it is. A JNI implementation could implement any subset
formance from various permutations, given 10,000 trials.
Table 124. Time to calculate the error of the random method
calculateError Calc Random JNI transitions Total time
Java
Java Java
0
12.4 seconds
Java
Java C
10,000,000
32.1 seconds
Java
C
C
10,000
24.4 seconds
C
Java Java
10,000
12.4 seconds
C
C
C
0
12.4 seconds