1

I have a single validation class which has various validate methods. like

public class GlobalValidationClass {

public void validatefields(String s) {
//My Work here
}

In methods of other classes, I create an instance of the above class and then call the validatefields method.

Like

public class FirstClass {

public void firstPage() {
    GlobalValidationClass fp = new GlobalValidationClass();
    fp.validatefields("first page");
}

public void secondPage() {
    GlobalValidationClass sp = new GlobalValidationClass();
    sp.validatefields("second page");
}

My question is will it increase performance if I make the methods in my validation class static? Or it wont as the java's garbage collector will garbage collect the objects at the end of each method and there wont be any performance impact if I am following the approach of creating instance of classes in every method?

4

5 回答 5

4

如果您在我的验证中使用方法,它将提高class static性能,但另一方面,一旦您的程序开始到程序结束,内存就会增加(取决于static方法和变量),因为静态获取内存。

并使用它的好工具jvisualvm获取统计信息,默认情况下它位于 /jdk/bin/

于 2012-08-02T06:48:23.913 回答
1

使用方法将有助于提高性能static,因为您不必创建对象或垃圾收集它们。

当一个类只有静态方法时,它被称为实用程序类。通常,你也给它一个private构造函数,以强调你不应该创建一个实例。

还有另一种选择:您可以通过重用验证器重构您的客户端类以最小化创建/破坏:

public class FirstClass {
    // Create the validator once per client instance, 
    // instead of once per method call
    private GlobalValidationClass fp = new GlobalValidationClass();

    public void firstPage() {
        fp.validatefields("first page");
    }

    public void secondPage() {
        sp.validatefields("second page");
    }
于 2012-08-02T06:45:18.470 回答
0

如果您没有任何特定的对象状态,则可以使用静态方法。每次创建一个对象然后调用执行相同操作的方法是用静态方法替换它的完美用例。它是一个更具可扩展性的解决方案。

于 2012-08-02T07:01:06.900 回答
0

如果没有与该验证类关联的状态信息(没有成员变量)并且如果只有一个验证方法,那么为什么不将其设为静态(一个实用程序类)另外,当您谈论性能时,您显然是在避免创建新的开销对象(性能增益可能取决于这些 firstpage() secondPage() 方法被调用的频率)并且也不需要垃圾收集它们:)

于 2012-08-02T07:12:41.770 回答
0

Firstly, have you identified this code as being a performance bottle neck? Remember, you shouldn't prematurely optimize!

Realistically, I wouldn't expect you to see much performance gain by making a method static. But the only way to find out is to measure it.

于 2012-08-02T06:54:00.247 回答