Advertisement
Guest User

Untitled

a guest
Feb 12th, 2013
262
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.13 KB | None | 0 0
  1. public class FieldTest {
  2.    
  3.     private int value = 0;
  4.    
  5.     public void setValue(int value) {
  6.         this.value = value;
  7.     }
  8.    
  9.     public int getValue() {
  10.         return this.value;
  11.     }
  12.    
  13.     public static long testFieldAccess(int num) {
  14.         FieldTest f = new FieldTest();
  15.        
  16.         long start = System.nanoTime();
  17.        
  18.         for (int i = 0; i < num; i++) {
  19.             f.value = f.value + 1;
  20.         }
  21.         f.value = 0;
  22.        
  23.         return System.nanoTime() - start;
  24.     }
  25.    
  26.     public static long testMethodAccess(int num) {
  27.         FieldTest f = new FieldTest();
  28.        
  29.         long start = System.nanoTime();
  30.        
  31.         for (int i = 0; i < num; i++) {
  32.             f.setValue(f.getValue() + 1);
  33.         }
  34.         f.setValue(0);
  35.        
  36.         return System.nanoTime() - start;
  37.     }
  38.    
  39.     public static void main(String[] args) {
  40.         int num = 2147483647;
  41.        
  42.         // "warn up" the VM
  43.         FieldTest f = new FieldTest();
  44.         f.value = 0;
  45.         f.setValue(0);
  46.         f.value = f.value;
  47.         f.setValue(f.getValue());
  48.        
  49.         // perform test
  50.         for (int i = 0; i < 10; i++) {
  51.             System.out.printf("Field Access:  %d ns\n", testFieldAccess(num));
  52.             System.out.printf("Method Access: %d ns\n", testMethodAccess(num));
  53.             System.out.println();
  54.         }
  55.     }
  56.  
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement