Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class FieldTest {
- private int value = 0;
- public void setValue(int value) {
- this.value = value;
- }
- public int getValue() {
- return this.value;
- }
- public static long testFieldAccess(int num) {
- FieldTest f = new FieldTest();
- long start = System.nanoTime();
- for (int i = 0; i < num; i++) {
- f.value = f.value + 1;
- }
- f.value = 0;
- return System.nanoTime() - start;
- }
- public static long testMethodAccess(int num) {
- FieldTest f = new FieldTest();
- long start = System.nanoTime();
- for (int i = 0; i < num; i++) {
- f.setValue(f.getValue() + 1);
- }
- f.setValue(0);
- return System.nanoTime() - start;
- }
- public static void main(String[] args) {
- int num = 2147483647;
- // "warn up" the VM
- FieldTest f = new FieldTest();
- f.value = 0;
- f.setValue(0);
- f.value = f.value;
- f.setValue(f.getValue());
- // perform test
- for (int i = 0; i < 10; i++) {
- System.out.printf("Field Access: %d ns\n", testFieldAccess(num));
- System.out.printf("Method Access: %d ns\n", testMethodAccess(num));
- System.out.println();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement