public class Run { public static void main(String[] args) { int result = 0; // Static call long t1 = System.currentTimeMillis(); for (int i = 0; i<100000; i++) { result = Item.run(); } long t2 = System.currentTimeMillis(); System.out.println("Item.run() time: " + (t2 - t1) + " ms."); // Instance call long t3 = System.currentTimeMillis(); for (int i = 0; i<100000; i++) { result = new Item2().run(); } long t4 = System.currentTimeMillis(); System.out.println("new Item().run() time: " + (t4 - t3) + " ms.");} } class Item { public static int run() { return (1 + 1); } } class Item2 { public int run() { return (1 + 1); } }A typical result looks like: Item.run() time: 30 ms. new Item2().run() time: 351 ms.What to gather from the results You can make your own conclusion as to which type of method to code. But, with this little experiment, the static call runs much faster than the instance method call. For obvious reasons: inline methods run a bit much faster, as there is no run time method binding. Also, we hear that object creation is expensive, and it is, plus you add the late method binding and there is more to do. However, this result doesn't mean that object instantiation needs to be avoided or replaced with inline method calls. It usually doesn't get you order of magnitude performance gains, hence, performance experts suggest to use inline method definition sparingly. Now, back to static vs. instantiated method calls. I code them all the time and usually put them in utility classes. I.e. Date transformation routines, which don't belong anywhere else. Do you use static methods? I almost forgot In Java, you can define a method static and still be able to call the method through an instance of the object (Provided, your constructors are not defined private - Nifty trick to avoid instantiation of some classes). |
Guestbook | Copyright ©
Jose Sandoval 2005 - jose@josesandoval.com |