繁体   English   中英

使用java:import static时的任何性能问题

[英]Any Performance Issue in using java : import static

我们在代码中经常使用util函数和一些功能,如Logger,EventWriter,Some Common DB调用等。 我更喜欢这些函数是静态的,因为在我的每一个代码中实例化这些类中的函数都会造成严重的性能损失(是不是?!!!?,我在stackoverflow中读到太多的类实例会是一个性能打击,我正在开发一个具有大客户数据库和服务器上的高访问日志的项目。 static import in java遇到了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");           
    }
}

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

  • 您将可能较大的类的内容转储到当前的命名空间中,使您的代码更难以阅读; 现代IDE通过单击程序中的名称导航到对象的定义来缓解这种情况。
  • 您的代码依赖于static对象,因此很难进行测试。 例如,您无法轻松删除模拟记录器,并希望您的代码开始使用它。 这是使用静态对象的一般限制 - 当您使用静态对象时,无论是否使用静态导入,都可以获得静态对象。

你的问题的答案是:

没有。

不,它不会产生任何性能问题。 但最好使用普通导入请不要使用此功能,因为在一段时间内你可能无法理解哪个静态方法或静态属性属于java程序中的哪个类。 该程序可能变得不可读。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM