c# – 更改具有“return”和“yield return”的方法

前端之家收集整理的这篇文章主要介绍了c# – 更改具有“return”和“yield return”的方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我知道在同一方法中使用return和yield return是不可能的.

这是我想要优化的代码

  1. public IEnumerable<TItem> GetItems(int data)
  2. {
  3. if (this.isSingleSet)
  4. {
  5. return this.singleSet; // is IEnumerable per-se
  6. }
  7. else
  8. {
  9. int index = this.GetSet(data);
  10. foreach(TKey key in this.keySets[index])
  11. {
  12. yield return this.items[key];
  13. }
  14. }
  15. }

重要提示:我知道此代码无法编译.这是我必须优化的代码.

我知道有两种方法可以使这种方法起作用:

>转换收益率返回部分:

  1. ...
  2. else
  3. {
  4. int index = this.GetSet(data);
  5. return this.keySets[index].Select(key => this.items[key]);
  6. }

>转换返回部分:

  1. if (this.isSingleSet)
  2. {
  3. foreach(TItem item in this.singleSet)
  4. {
  5. yield return item;
  6. }
  7. }
  8. else ...

但两者之间存在很大的速度差异.仅使用return语句(换句话说使用Select())要慢得多(比如慢6倍)才能产生返回转换.

有没有其他方法让你想到如何编写这个方法?您是否有任何其他建议信息对性能差异有价值?

附加信息

我正在围绕for循环使用秒表来测量两种方法的速度.

  1. Stopwatch s = new Stopwatch();
  2. s.Start();
  3. for(int i = 0; i < 1000000; i++)
  4. {
  5. GetItems(GetRandomData()).ToList();
  6. }
  7. s.Stop();
  8. Console.WriteLine(s.ElapsedMilliseconds);

每个循环都在不同的进程中运行,因此垃圾收集或其他任何东西都可能没有性能影响.

>然后我用一个方法版本运行程序
>关闭
>重写方法并再次运行.

这几次看到可靠的性能差异……

解决方法

使用两个功能.由客户端调用的外部函数执行您不想延迟的所有非惰性位(如参数验证).私人工作者做懒惰的事情:
  1. public IEnumerable<TItem> GetItems(int data) {
  2. if (this.isSingleSet) {
  3. return this.singleSet; // is IEnumerable per-se
  4. } else {
  5. return DoGetItems(data);
  6. }
  7. }
  8.  
  9. private IEnumerable<TItem> DoGetItems(int data) {
  10. int index = this.GetSet(data);
  11. foreach(TKey key in this.keySets[index]) {
  12. yield return this.items[key];
  13. }
  14. }

猜你在找的C#相关文章