7

我们确实在我们的代码中经常使用 util 函数和一些功能,如 Logger、EventWriter、一些常见的 DB 调用等。我更喜欢这些函数是静态的,因为在我的每个代码中从这些类中实例化函数会严重影响性能(会不会是 ?!!!?,我在 stackoverflow 中读到过多的类实例化会受到性能影响,我正在开发一个具有大型客户数据库和服务器上的高访问日志的项目)。而且我遇到了static import in java看起来很酷的东西,我想知道:在使用它之前是否有任何严重的考虑?

我已经从 StackOverFlow 收集到的东西:

使用静态导入可能会使代码不可读,例如判断函数定义。

除此之外,我必须担心的任何漂亮问题..?

旧代码:

class myservlet extends httpServlet
{
    pubilc doPost()
    {
        Utils utils = new Utils();
        DBFuncs dbFuncs = new dbFuncs();
        Logger logger = new Logger();
        EventWrtr eventWrtr = new EventWriter();

        utils.GetEscapedName(name);
        logger.Log("error");
        eventWrtr.WriteEvent("something happened");
        // Getting new Objects for every servlet calls

    }
}

我当前的代码:(希望这将避免不必要的实例化,代码就像上面一样,我现在正在更改它)

/* Declaring all the methods in the below classes as static methods */  
import com.mycom.Utils;
import com.mycom.DBFuncs;
import com.mycom.Logger;
import com.mycom.EventWrtr;
class myservlet extends httpServlet
{
    public doPost()
    {
        Utils.GetEscapedName(name);
        Logger.Log("error");
        EventWrtr.WriteEvent("something happened");         
    }
}

我有点喜欢这样,我想知道任何严重问题,尤其是与使用以下方法相关的性能

/* Declaring all the methods in the below classes as static methods */  
import static com.mycom.Utils;
import static com.mycom.DBFuncs;
import static com.mycom.Logger;
import static com.mycom.EventWrtr;
class myservlet extends httpServlet
{
    public doPost()
    {
        GetEscapedName(name);
        Log("error");
        WriteEvent("something happened");           
    }
}
4

3 回答 3

16

static import特性是一种语法糖特性,因此它不会对性能产生影响。但是,它确实对可读性和可测试性产生了负面影响:

  • 你将一个可能很大的类的内容转储到你当前的命名空间中,使你的代码更难阅读;现代 IDE 通过让您通过在程序中单击对象的名称来导航到对象的定义来缓解这种情况。
  • Your code relies upon static objects, making it extremely hard to test. For example, you cannot easily drop a mock logger, and expect your code start using it. This is a general limitation of using static objects, though - you get it when you use static objects, with or without the static import.
于 2012-12-14T15:12:53.780 回答
7

The answer to your question is:

No.

于 2012-12-14T15:13:30.257 回答
2

no it will not make any performance issue. but its better to use normal import Please don’t use this feature, because over a period you may not understand which static method or static attribute belongs to which class inside the java program. The program may become unreadable.

于 2014-01-08T12:43:25.233 回答