Man*_*san 6 java import performance static
我们在代码中经常使用util函数和一些功能,如Logger,EventWriter,Some Common 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
}
}
Run Code Online (Sandbox Code Playgroud)
我当前的代码:(希望这会避免不必要的实例化,代码就像上面那样,我现在正在改变它)
/* 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");
}
}
Run Code Online (Sandbox Code Playgroud)
我有点像这样,我想知道任何严重问题,尤其是使用以下方法相关的性能
/* 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");
}
}
Run Code Online (Sandbox Code Playgroud)
das*_*ght 13
该static import功能是一种语法糖类功能,因此不会产生性能影响.但它确实对可读性和可测试性产生了负面影响:
static对象,因此非常难以测试.例如,您无法轻松删除模拟记录器,并希望您的代码开始使用它.这是使用静态对象的一般限制 - 当您使用静态对象时,无论是否使用静态导入,都可以获得静态对象.| 归档时间: |
|
| 查看次数: |
1976 次 |
| 最近记录: |