这两个 GetLargestValue C# 实现哪一个更好,为什么?

发布于 2024-07-08 06:16:15 字数 698 浏览 7 评论 0原文

对于如何最好地实现一个接受整数数组并返回最大整数的简单方法(使用 C# 2.0),我与某人存在分歧。

以下是两个实现 - 我对哪个更好以及为什么更好有自己的看法,但我会感谢任何公正的意见。

选项A

public int GetLargestValue(int[] values)
{
   try  {
          Array.Sort(values);
          return values[values.Length - 1];
        }
   catch (Exception){ return -1;}
}

选项B

public int GetLargestValue(int[] values)
{
    if(values == null)
        return -1;

    if(values.Length < 1)
        return -1;

    int highestValue = values[0];

    foreach(int value in values)
        if(value > highestValue)
            highestValue = value;

    return highestValue;
}

I'm having a disagreement with someone over how best to implement a simple method that takes an array of integers, and returns the highest integer (using C# 2.0).

Below are the two implementations - I have my own opinion of which is better, and why, but I'd appreciate any impartial opinions.

Option A

public int GetLargestValue(int[] values)
{
   try  {
          Array.Sort(values);
          return values[values.Length - 1];
        }
   catch (Exception){ return -1;}
}

Option B

public int GetLargestValue(int[] values)
{
    if(values == null)
        return -1;

    if(values.Length < 1)
        return -1;

    int highestValue = values[0];

    foreach(int value in values)
        if(value > highestValue)
            highestValue = value;

    return highestValue;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

哀由 2024-07-15 06:16:15

Ô选项B当然。

A 很丑陋:

  • Catch(Exception) 是一种非常糟糕的做法

  • 你不应该依赖 null ref、超出范围等异常,...< /p>

  • 排序比迭代复杂得多

复杂度:

  • A 将是 O(n log(n)),甚至在最坏情况下为 O(n²)

  • B 最坏情况是 O(n)< /p>

Ôption B of course.

A is ugly :

  • Catch(Exception) is a really bad practice

  • You shoul not rely on exception for null ref, out of range,...

  • Sorting is way complexier than iteration

Complexity :

  • A will be O(n log(n)) and even O(n²) in worst case

  • B worst case is O(n)

Spring初心 2024-07-15 06:16:15

A 具有对数组进行排序的副作用。 这可能是呼叫者意想不到的。

编辑:我不喜欢为空或空数组返回 -1 (在两种解决方案中),因为 -1 可能是数组中的合法值。 这确实应该生成一个异常(可能是 ArgumentException)。

A has the side effect that it sorts the array. This might be unexpected by the caller.

Edit: I don't like to return -1 for empty or null array (in both solutions), since -1 might be a legal value in the array. This should really generate an exception (perhaps ArgumentException).

烟酉 2024-07-15 06:16:15

我更喜欢选项 B,因为它只遍历集合一次。

选项A中,您可能必须多次访问许多元素(次数取决于排序算法的实现)。

选项 A 是一种低效的实现,但会产生相当清晰的算法。 然而,它确实使用了一个相当丑陋的异常捕获,只有在传入空数组时才会触发该异常捕获(因此可以通过预排序检查写得更清楚)。

PS,你永远不应该简单地捕获“异常”然后纠正错误。 异常有很多种类型,通常您应该捕获每种可能的异常并进行相应的处理。

I prefer Option B as it only traverses the collection exactly once.

In Option A, you may have to access many elements more than once (the number of times is dependant upon the implementation of the sort alogrithm).

The Option A is an inefficent implementation, but results in a fairly clear algorithm. It does however use a fairly ugly Exception catch which would only ever be triggered if an empty array is passed in (so could probably be written clearer with a pre-sort check).

PS, you should never simply catch "Exception" and then correct things. There are many types of Exceptions and generally you should catch each possible one and handle accordingly.

看透却不说透 2024-07-15 06:16:15

第二个更好。
第一个的复杂度是O(N LogN),第二个的复杂度是O(N)

The second one is better.
The complexity of the first is O(N LogN), and for the second it is O(N).

梦里寻她 2024-07-15 06:16:15

我必须选择选项 B - 并不是因为它是完美的,而是因为选项 A 使用异常来表示逻辑。

I have to choose option B - not that it's perfect but because option A uses exceptions to represent logic.

蓝颜夕 2024-07-15 06:16:15

我想说这取决于你的目标是什么,速度或可读性。

如果处理速度是您的目标,我会选择第二个解决方案,但如果可读性是目标,我会选择第一个解决方案。

我可能会追求这种类型功能的速度,所以我会选择第二个。

I would say that it depends on what your goal is, speed or readability.

If processing speed is your goal, I'd say the second solution, but if readability is the goal, I'd pick the first one.

I'd probably go for speed for this type of function, so I'd pick the second one.

凉城 2024-07-15 06:16:15

这里有很多因素需要考虑。 这两个选项都应包含选项 B 中的边界检查,并消除以这种方式使用异常处理。 第二个选项在大多数情况下应该表现更好,因为它只需要遍历数组一次。 但是,如果数据已经排序或需要排序; 那么选项 A 会更可取。

没有排序算法在 n 时间内执行,因此选项 B 平均来说是最快的。

编辑:有关排序的文章

There are many factors to consider here. Both options should include the bounds checks that are in option B and do away with using Exception handling in that manner. The second option should perform better most of the time as it only needs to traverse the array once. However, if the data was already sorted or needed to be sorted; then Option A would be preferable.

No sorting algorithm performs in n time, so Option B will be the fastest on average.

Edit: Article on sorting

走走停停 2024-07-15 06:16:15

我在这里看到两点:

  1. 参数测试而不是异常处理:更好地使用显式检查,也应该更快。
  2. 排序并选取最大值,而不是遍历整个数组。 由于排序涉及处理数组中的每个整数至少一次,因此它的执行效果不如(仅)遍历整个数组一次。

哪个更好? 对于第一点,绝对是显式检查。 对于第二个,这取决于...

第一个示例较短,可以更快地编写和阅读/理解。 第二个更快。 因此:如果运行时效率是一个问题,请选择第二个选项。 如果快速编码是您的目标,请使用第一个。

I see two points here:

  1. Parameter testing as opposed to exception handling: Better use explicit checking, should also be faster.
  2. Sorting and picking the largest value as opposed to walking the whole array. Since sorting involves handling each integer in the array at least once, it will not perform as well as walking the whole array (only) once.

Which is better? For the first point, definitely explicit checking. For the second, it depends...

The first example is shorter, makes it quicker to write and read/understand. The second is faster. So: If runtime efficiency is an issue, choose the second option. If fast coding is your goal, use the first one.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文