请选择 进入手机版 | 继续访问电脑版

技术控

    今日:35| 主题:54646
收藏本版 (1)
最新软件应用技术尽在掌握

[其他] Is using ‘using’ block really helpful?

[复制链接]
百里梨花 发表于 2016-10-13 10:57:03
326 7

立即注册CoLaBug.com会员,免费获得投稿人的专业资料,享用更多功能,玩转个人品牌!

您需要 登录 才可以下载或查看,没有帐号?立即注册

x
Introduction and Background

  So, it all began on the Facebook when I was posting a status (using Twitter) about a statement that I was feeling very bad that .NET team had left out the “Close” function while designing their .NET Core framework. At first I thought maybe everything was “managed” underground until I came up to an exception telling me that the file was already being used. The code that I was using was something like this,
  1. if(!File.Exists("path")) { File.Create("path").Close(); }
复制代码
However, “Close” was not defined and I double checked against .NET Core reference documentations too, and they suggested that this was not available in .NET Core framework. So I had to use other end… Long story short, it all went up like this,
  I am unable to understand why was “Close” function removed from FileStream. It can be handy guys, @dotnet.
  Then, Vincent came up with the idea of saying that “Close” was removed so that we all can use “using” blocks, which are much better in many cases.
   You don’t need that. It’s handier if you just put any resource that eats resources within the “using block”.  ��  
  Me:
  How does using, “using (var obj = File.Create()) { }” make the code handier?
  I was talking about this, “File.Create().Close();”
   Now, instead of this, we have to flush the stream, or perform a flush etc. But I really do love the “using block” suggestion, I try to use it as much as I can. Sometimes, that doesn’t play fair.  :wink:  
  He:
   Handier because I don’t have to explicitly call out the “Close()” function. Depends on the developer’s preference, but to me, I find “using (var obj = File.Create()) { }” handier and sexier to look at rather than the plain and flat “File.Create().Close();”. Also, it’s a best practice to “always” use the using block when dealing with objects that implements IDisposable to ensure that objects are properly closed and disposed when you’re done with it.  :wink:  
  As soon as you leave the using block’s scope, the stream is closed and disposed. The using block calls the Close() function under the hood, and the Close() calls the Flush(), so you should not need to call it manually.
  Me:
  I will go with LINQPad to see which one is better. Will let you know.
  So, now I am here, and I am going to share what I find in the LINQPad. The fact is that I have always had faith in the code that works fast and provides a better performance. He is an ASP.NET MVP on Microsoft and can be forgiven for the fact that web developers are trained on multi-core CPUs and multi-deca-giga-bytes of RAMs so they use the code that looks cleaner but… He missed the C# bytecode factor here. I am going to use LINQPad to find out the underlying modifications that can be done to find out a few things.
   Special thanks to Vincent: Since a few days I was out of topics to write on, Vincent you gave me one and I am going to write on top of that debate that we had.
   Notice: I also prefer using the “using” block in almost every case. Looks handier, but the following code block doesn’t look handier at all,
  1. using (var obj = File.Create("path")) { }
复制代码
And this is how it began…
  Exploring the “using” and simple “Close” calls

  LINQPad is a great software to try out the C# (or .NET framework) code and see how it works natively, it lets you see the native bytecode of ,NET framework and also lets you perform and check the tree diagrams of the code. The two types that we are interested in are, “using” statement of .NET framework and the simple “Close” calls that are made to the objects to close their streams.
  I used a Stopwatch object to calculate the time taken by the program to execute each task, then I match the results of each of the program with each other to find out which one went fast. Looking at the code of them both, it looks the thousand-feet high view of them both looks the same,
  1. // The using block
  2. using (var obj = File.Create("path")) { }

  3. // The clock method
  4. File.Create("path").Close();
复制代码
They both the same, however, their intermediate code shows something else.
  1. // IL Code for "using" block
  2. IL_0000: nop
  3. IL_0001: ldstr "F:/File.txt"
  4. IL_0006: call System.IO.File.Create
  5. IL_000B: stloc.0 // obj
  6. IL_000C: nop
  7. IL_000D: nop
  8. IL_000E: leave.s IL_001B
  9. IL_0010: ldloc.0 // obj
  10. IL_0011: brfalse.s IL_001A
  11. IL_0013: ldloc.0 // obj
  12. IL_0014: callvirt System.IDisposable.Dispose
  13. IL_0019: nop
  14. IL_001A: endfinally
  15. IL_001B: ret

  16. // IL Code for the close function
  17. IL_0000: nop
  18. IL_0001: ldstr "F:/File.txt"
  19. IL_0006: call System.IO.File.Create
  20. IL_000B: callvirt System.IO.Stream.Close
  21. IL_0010: nop
  22. IL_0011: ret
复制代码
Oh-my-might-no! There is no way, “using” block could have ever won with all of that extra intermediate code for the .NET VM to execute before exiting. The time taken by these commands was also tested and for that I used the native Stopwatch object to calculate the “ticks” used, instead of the time in milliseconds by each of the call. So my code in the LINQPad looked like this,
  1. void Main()
  2. {
  3.    Stopwatch watch = new Stopwatch();
  4.    watch.Start();
  5.    using (var obj = File.Create("F:/file.txt")) { }
  6.    watch.Stop();
  7.    Console.WriteLine($"Time required for 'using' was {watch.ElapsedTicks}.");

  8.    watch.Reset();
  9.    watch.Start();
  10.    File.Create("F:/file.txt").Close();
  11.    watch.Stop();
  12.    Console.WriteLine($"Time required for 'close' was {watch.ElapsedTicks}.");
  13. }
复制代码
The execution of the above program always results in a win for the “Close” function call. In sometimes it was a close result, but still “Close” function had a win over the “using” statement. The results are shown the images below,
   

Is using ‘using’ block really helpful?

Is using ‘using’ block really helpful?-1-技术控-understand,everything,framework,Facebook,something

Is using ‘using’ block really helpful?

Is using ‘using’ block really helpful?-2-技术控-understand,everything,framework,Facebook,something

Is using ‘using’ block really helpful?

Is using ‘using’ block really helpful?-3-技术控-understand,everything,framework,Facebook,something

  The same executed, produced different results, there are many factors to this and it can be forgiven for all of them,
  
       
  • Operating system might put a break to the program for its own processing.   
  • Program might not be ready for processing.   
  • Etc. etc. etc.  
  There are many reasons. For example, have a look at the last image, the time taken was 609 ticks. Which also includes the ticks taken by other programs. The stopwatch was running ever since, and that is what caused the stopwatch to keep tracking the ticks. But in any case, “using” statement was not a better solution from a low level code side.
  Final words

  Although I also recommend using the “using” block statement in C# programs, but there is a condition where you should consider using one over other. For example, in this condition, we see that implementing one over the other has no benefit at all, but just a matter of personal interest and like. Although I totally agree to Vincent where he mentions that “using” block is helpful, but in other cases. In this case, adding a Close call is a cleaner (IMO) way of writing the program as compared to the other one.
  At the end, it is all in the hands of the writer… Select the one you prefer.



上一篇:A Quick Understanding of REST
下一篇:BinaryTree:学习二叉树的Python库
廖子华 发表于 2016-10-24 05:37:58
十分赞同楼主!
回复 支持 反对

使用道具 举报

shennianxu 发表于 2016-11-14 13:47:47
好贴,绝对要支持下
回复 支持 反对

使用道具 举报

ycx7758521 发表于 2016-11-16 17:59:41
看帖要回,回帖才健康,我使劲踩,楼主辛苦了!
回复 支持 反对

使用道具 举报

63785863 发表于 2016-11-17 16:42:19
男女关系处理得好会传出佳话,处理得不好会传出闲话。
回复 支持 反对

使用道具 举报

chenbang879 发表于 2016-11-17 22:38:46
作为一个曾经充分理解怎么吃也不胖的瘦子,如今我总算完全的体会了一吃就胖的感悟。
回复 支持 反对

使用道具 举报

沛白 发表于 2016-11-18 22:33:54
什么啊,语文是苍老师教的吗?
回复 支持 反对

使用道具 举报

目送妳旳愛※ 发表于 2016-11-21 18:13:27
百里梨花看起来很有学问!
回复 支持 反对

使用道具 举报

*滑动验证:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

我要投稿

推荐阅读


回页顶回复上一篇下一篇回列表
手机版/CoLaBug.com ( 粤ICP备05003221号 | 文网文[2010]257号 )

© 2001-2017 Comsenz Inc. Design: Dean. DiscuzFans.

返回顶部 返回列表