这是双重瞬时有害的,还是简单的不必要? [英] Is this double instantation harmful, or simply unnecessary?

查看:113
本文介绍了这是双重瞬时有害的,还是简单的不必要?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  DataSet myUPC = new DataSet(); 
myUPC = dbconn.getDataSet(dynSQL);

Resharper正确地灰色化了新数据集()部分,并建议删除多余的initalizer,但它是如此无害吗?编译器是否在第二次分配之前简单地处理第一个实例? IOW,第一个赋值是不必要的,还是可能有害?

解决方案


编译器在第二次分配之前简单地处理第一个实例?

不,这里没有自动处理。


IOW,是第一项任务,不是必要的,还是可能有害?

这有害于两个小方面:


  • 它为初始化代码和垃圾收集器都做了更多的工作。这不太可能是重要的,但它在那里。如果构造函数获得了一些可能更严重的本地资源,那么它会让你的代码看起来像它想做的事情,它并不真正想做的事情。您不想创建一个新的空 DataSet ,那么为什么要这样做呢?



  DataSet myUPC = dbconn.getDataSet(dynSQL);使用您想要的值初始化变量。 

现在您的代码完全显示您想要执行的操作。 (我会修复方法名称,以便遵循.NET命名约定,请注意。)


While perusing the legacy source, I found this:

DataSet myUPC = new DataSet();
myUPC = dbconn.getDataSet(dynSQL);

Resharper rightly "grays out" the "new Dataset()" part of it, and recommends, "Remove redundant initalizer," but is it as innocuous as that? Does the compiler simply dispose of the first instance just prior to the second assignment? IOW, is the first assignment simply unnecessary, or is it potentially harmful?

解决方案

Does the compiler simply dispose of the first instance just prior to the second assignment?

No, there's no automatic disposal here.

IOW, is the first assignment simply unnecessary, or is it potentially harmful?

It's harmful in two small ways:

  • It makes more work for both the initialization code and the garbage collector. It's unlikely to be significant, but it's there. If the constructor acquired some native resource that could be more serious.
  • It makes your code look like it wants to do something it doesn't actually want to do. You don't want to create a new empty DataSet, so why do so?

Just initialize the variable with the value you really want:

DataSet myUPC = dbconn.getDataSet(dynSQL);

Now your code shows exactly what you want to do. (I would fix the method name so that it follows .NET naming conventions, mind you.)

这篇关于这是双重瞬时有害的,还是简单的不必要?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆