【问题标题】:What would be the best way to use string functions and alteration on one string?在一个字符串上使用字符串函数和更改的最佳方法是什么?
【发布时间】:2010-10-31 13:09:38
【问题描述】:

编写代码的最佳方式应该是什么:

1)

Dim current = Request.Path
current = current.Remove(0, 1)
current = current.Replace(".aspx", "")

2)

Dim current = Request.Path.Remove(0, 1).Replace(".aspx", "")

3)

Dim current = Request.Path
Dim current2 = current.Remove(0, 1)
Dim current3 = current.Replace(".aspx", "")

或者1-2没有区别?

【问题讨论】:

    标签: .net performance string concatenation string-concatenation


    【解决方案1】:

    这些都是一样的。试试

    Path.GetFileNameWithoutExtension(Request.Path)
    

    【讨论】:

      【解决方案2】:

      三者基本相同。

      记住字符串是不可变的。每次调用字符串上的方法时,它都会分配一个新的字符串对象,因此调用Remove()会创建一个新对象,然后使用该对象调用Replace()

      1 & 2 基本相同。 #3 有点不同,因为您使用 3 个单独的变量,因此您保留对这些字符串的引用,以便以后使用它们。垃圾收集器应该知道如何处理所有 3 个示例并大致相同地处理它们,但无论您是否将中间字符串存储为变量。

      我会使用 #2,只是因为它的代码行数更少并且不会牺牲可读性,但它仍然是相当短的代码。

      【讨论】:

        【解决方案3】:

        这些调用可能会引发异常。对于玩具代码,可以不检查,但是在获得路径后,您应该在调用 Remove 之前检查 String.NullOrEmpty 和长度。所以,这就是为什么我会避免#2。除此之外,#1 看起来更干净,除非您需要在方法中的其他位置使用中间值(当前作为路径和当前 2)。

        【讨论】:

          【解决方案4】:

          字符串在 .Net 中是不可变的,因此您可以从所有这些方法中获得相同的性能。

          【讨论】:

            猜你喜欢
            • 2015-01-11
            • 1970-01-01
            • 1970-01-01
            • 2022-01-15
            • 1970-01-01
            • 2011-10-03
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多