生成随机字符串非常慢

时间:2014-07-13 12:06:12

标签: vb.net string text random numbers

我喜欢在vb.net中生成一个随机字符串。 我已经编写了一个完成这项工作的功能:

enter image description here

但这种生成随机字符串的方式非常慢,对于~5个文本框,生成字符串需要将近一秒钟。 我怎样才能加快我的代码速度?

感谢每一位帮助:)

5 个答案:

答案 0 :(得分:1)

所以我测试了它。不到一秒钟就能生成100个,200个字符的字符串。

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim stpw As Stopwatch = Stopwatch.StartNew
    For x As Integer = 1 To 100
        TextBox1.Text = RandomString(200)
        TextBox1.Refresh()
    Next
    stpw.Stop()
    Debug.WriteLine(stpw.Elapsed)
End Sub

Dim prng As New Random
Private Function RandomString(desiredLength As Integer) As String
    Dim CharSet As String = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
    Dim rv As New System.Text.StringBuilder

    For ct As Integer = 1 To desiredLength
        rv.Append(CharSet(prng.Next(0, CharSet.Length)))
    Next
    Return rv.ToString
End Function

编辑:新测试,小于一毫秒,即使按下按钮的速度尽可能快。

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim stpw As Stopwatch = Stopwatch.StartNew
    TextBox1.Text = RandomString(200)
    TextBox2.Text = RandomString(200)
    TextBox3.Text = RandomString(200)
    stpw.Stop()
    Debug.WriteLine(stpw.Elapsed)
End Sub

答案 1 :(得分:1)

这是我的方法:

Dim Randomizer As New Random

' Get Random String
' // By Elektro
'
' Usage Examples :
' MsgBox(GetRandomString("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", 10))
' MsgBox(GetRandomString("abcdefghijklmnopqrstuvwxyz", 10, True))
'
''' <summary>
''' Gets a random string.
''' </summary>
''' <param name="CharacterSet">Indicates the characters to randomize.</param>
''' <param name="StringLength">Indicates the resulting string length.</param>
''' <param name="RandomizeCase">If set to <c>true</c>, lower-case and upper-case are randomized.</param>
''' <returns>System.String.</returns>
''' <exception cref="System.Exception">
''' CharacterSet is empty.
''' or
''' String-Length must be greater than 0.
''' </exception>
Private Function GetRandomString(ByVal CharacterSet As Char(),
                                 ByVal StringLength As Integer,
                                 Optional ByVal RandomizeCase As Boolean = False) As String

    Select Case CharacterSet.Count

        Case Is = 0
            Throw New Exception("CharacterSet is empty.")

        Case Is = 1
            Return New String(CharacterSet.First, Math.Abs(StringLength))

        Case Else

            Select Case StringLength

                Case Is < 1
                    Throw New Exception("String-Length must be greater than 0.")

                Case Else

                    Dim CharSetLength As Integer = CharacterSet.Length
                    Dim CharSB As New System.Text.StringBuilder

                    Do Until CharSB.Length = StringLength

                        If Not RandomizeCase Then
                            CharSB.Append(CharacterSet(Randomizer.Next(0, CharSetLength)))

                        Else

                            Select Case Randomizer.Next(0, 2)

                                Case 0 ' Lower-Case
                                    CharSB.Append(Char.ToLower(CharacterSet(Randomizer.Next(0, CharSetLength))))

                                Case 1 ' Upper-Case
                                    CharSB.Append(Char.ToUpper(CharacterSet(Randomizer.Next(0, CharSetLength))))

                            End Select

                        End If '/ Not RandomizeCase

                    Loop '/ CharSB.Length = StringLength

                    Return CharSB.ToString

            End Select '/ StringLength

    End Select '/  CharacterSet.Count

End Function

答案 2 :(得分:0)

我不熟悉VB及其语法,但这里有一些你可能能够转换的c#代码。我不确定这会有多快。

    var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
    var random = new Random(Guid.NewGuid().GetHashCode());
    var randomString = new string(
        Enumerable.Repeat(chars, 20)
                  .Select(s => s[random.Next(s.Length)])
                  .ToArray());
    return randomString ;

答案 3 :(得分:0)

试试:

Dim chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz"
Dim random = New Random(Guid.NewGuid().GetHashCode())
Dim randomString = New String(Enumerable.Repeat(chars, 20).[Select](Function(s) s(random.[Next](s.Length))).ToArray())
Return randomString

答案 4 :(得分:0)

您还可以使用Random.NextBytes方法,如下所示:

Dim rnd As New System.Random

Private Function NewRandomString(ByVal length As Integer) As String
    If length <= 0 Then Return ""
    Dim CharSet As String = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
    Dim GenRandomStr As New StringBuilder
    Dim RandomBytes(length - 1) As Byte
    rnd.NextBytes(RandomBytes)

    For i As Integer = 0 To length - 1
        GenRandomStr.Append(CharSet(RandomBytes(i) Mod CharSet.Length))
    Next

    Return GenRandomStr.ToString
End Function

要比较此功能的速度,请使用以下代码:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim Stopwatch As New Stopwatch
    Stopwatch.Start()

    For i As Integer = 1 To 100000
        RandomString(200)
    Next

    Stopwatch.Stop()
    MsgBox("Original time [" & Stopwatch.Elapsed.ToString() & "]")

    Stopwatch.Reset()
    Stopwatch.Start()

    For i As Integer = 1 To 100000
        NewRandomString(200)
    Next

    Stopwatch.Stop()
    MsgBox("New time [" & Stopwatch.Elapsed.ToString() & "]")
End Sub

对于100000次迭代(在i7 4770k上),我得到了时间:

Original time [00:00:00.5434907]
     New time [00:00:00.3569711]

快34%