PHP User Warning: fetch_template() calls should be replaced by the vB_Template class. Template name: bbcode_highlight in ..../includes/functions.php on line 4197

PHP User Warning: fetch_template() calls should be replaced by the vB_Template class. Template name: bbcode_highlight in ..../includes/functions.php on line 4197

PHP User Warning: fetch_template() calls should be replaced by the vB_Template class. Template name: bbcode_highlight in ..../includes/functions.php on line 4197

PHP User Warning: fetch_template() calls should be replaced by the vB_Template class. Template name: bbcode_highlight in ..../includes/functions.php on line 4197

PHP User Warning: fetch_template() calls should be replaced by the vB_Template class. Template name: bbcode_highlight in ..../includes/functions.php on line 4197

PHP User Warning: fetch_template() calls should be replaced by the vB_Template class. Template name: bbcode_highlight in ..../includes/functions.php on line 4197
VS 2019 is it a Variable or an Array?-VBForums
Results 1 to 27 of 27

Thread: is it a Variable or an Array?

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Dec 2019
    Posts
    67

    is it a Variable or an Array?

    Originally written in VB 2010 (now using VS 2019), I am making changes to a program I wrote in about 2011 or so to attempt to speed it up. Currently I have been changing all the static arrays to dynamic arrays so that I can release the memory after the array is no longer needed.

    I noticed the following in the declarations area of my Module1 that has me confused.
    Code:
    Friend StrPadding(9) As Integer
    I cannot find any reference to variables having arguments (inside parenthesis) when I do internet searches relative to variables and Visual Basic. However, I cannot find where an array declaration uses anything other than "Dim". Sorry for such a dumb question, but is that an array or can variables have arguments inside parenthesis?

  2. #2
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    104,705

    Re: is it a Variable or an Array?

    It is both. It is a variable of type Integer array that refers to an Integer array object. This code declares an array variable:
    vb.net Code:
    1. Dim arr As SomeType()
    This code is functionally equivalent:
    vb.net Code:
    1. Dim arr() As SomeType
    When declaring an array variable, you can put the parentheses on either the variable or the type. Microsoft used to recommend the latter but they now recommend the former.

    An array variable is like any other variable. It is Nothing by default and you can create an object and assign that object to the variable. In order to create an array object, you MUST specify the length, either implicitly or explicitly. Doing so implicitly means creating a literal array and the size is determined by the number of literal elements, e.g.
    vb.net Code:
    1. Dim arr As Integer() = {1, 2, 3, 4, 5}
    Doing so explicitly means specifying the upper bound so the number of elements is known and each element is initialised to Nothing, e.g.
    vb.net Code:
    1. Dim arr As Integer() = New Integer(9) {}
    That code creates a new array with elements of type Integer and an upper bound of 9. A shorthand for that last code is this:
    vb.net Code:
    1. Dim arr(9) As Integer
    Look familiar? Your code is declaring a field (member variable) that is type Integer array, creating an array with an upper bound of 9 (length of 10) where each element is Nothing and then assigning that array object to the field. The field has an access level of Friend.

    Note that the Dim keyword denotes a variable, just like the Sub and Function keywords denote methods, the Property keyword denotes a property and the Event keyword denotes an event. Local variables use just the Dim keyword while member variables use it in conjunction with an access modifier, just as methods, properties and events do. Strictly speaking, the full declaration for your field is this:
    vb.net Code:
    1. Friend Dim StrPadding(9) As Integer
    The VB code editor used to allow that and, I think, still will if you have Pretty Listing (auto-formatting) turned off in the IDE options. A field is the default member kind though, so if you don't include a member specifier (Dim, Sub, Function, Property, Event) then it is assumed to be a field. For that reason, the Dim keyword is superfluous and omitted by default.

  3. #3
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    34,902

    Re: is it a Variable or an Array?

    Also, you probably won't gain a thing by "release the memory". Since it's cheaper for the program to get new memory than recycle used memory, what will probably happen when you "release the memory" is that the object will simply become unreachable. It will still be there, hanging around in memory, you just can't get to it. If new memory is not available, then the program will go through, find all those unreachable objects, and recover the memory. That's costly in time, though, so the program won't do that until it absolutely has to.

    One of the reasons it will be so costly is that you will likely end up with a bunch of small chunks of recoverable memory. There will be some memory used for objects that are still necessary distributed among the blocks of memory that are no longer in use. Once new memory is exhausted, the program will have to find a block of memory for any new object, which will likely mean taking all those existing objects and moving them around to pack them into a smaller area and free a large, contiguous, block of memory to use going forwards. It won't just be freeing memory, it will be moving a lot of stuff around, and before that, it will have to do some analysis to figure out how to move the stuff around.

    So, don't worry all that much about freeing memory. It generally doesn't provide any benefit.
    My usual boring signature: Nothing

  4. #4
    Fanatic Member
    Join Date
    Nov 2017
    Posts
    1,003

    Re: is it a Variable or an Array?

    Assuming this thread is related to this other thread http://www.vbforums.com/showthread.p...er-reaches-100

    The code you posted in that other thread that you were using was a little rough around the edges (to put it mildly).

    You later indicated that that code was intended to track a potential performance slowdown in your main custom encryption program.

    Not trying to be a d-bag or anything, but to be blunt, if the rest of the code in your program is of similar quality, then I doubt that the path you are headed down regarding arrays is going to speed things up noticeably.

    Good luck.

  5. #5
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    34,902

    Re: is it a Variable or an Array?

    Timing with the Stopwatch object is your friend.
    My usual boring signature: Nothing

  6. #6
    Fanatic Member
    Join Date
    Nov 2017
    Posts
    1,003

    Re: is it a Variable or an Array?

    Quote Originally Posted by Shaggy Hiker View Post
    Timing with the Stopwatch object is your friend.
    I think the OP got that sorted from the other thread.

    I think my point may have been missed.

    Imagine you have a friend who has built their own house. They tell you they are having some problems with it from a structural standpoint (leaks, drafts, etc.) So, they invite you over to help take a look, and, to assist with this, they present you with a scaffold that they also built themselves. You take one look at the scaffold and see some pretty significant concerns about its stability and point them out to your friend.

    Then, your friend says, "well, maybe the house just needs a new coat of paint."

    That's my point. If the scaffold (performance testing code from other thread) was built with questionable quality, no doubt the house (main encryption/decryption project) was as well, and a new coat of paint (futzing with arrays) is unlikely to resolve the underlying problems.

    Just my two cents.

  7. #7

    Thread Starter
    Lively Member
    Join Date
    Dec 2019
    Posts
    67

    Re: is it a Variable or an Array?

    Quote Originally Posted by OptionBase1 View Post
    I think the OP got that sorted from the other thread.

    I think my point may have been missed.

    Imagine you have a friend who has built their own house. They tell you they are having some problems with it from a structural standpoint (leaks, drafts, etc.) So, they invite you over to help take a look, and, to assist with this, they present you with a scaffold that they also built themselves. You take one look at the scaffold and see some pretty significant concerns about its stability and point them out to your friend.

    Then, your friend says, "well, maybe the house just needs a new coat of paint."

    That's my point. If the scaffold (performance testing code from other thread) was built with questionable quality, no doubt the house (main encryption/decryption project) was as well, and a new coat of paint (futzing with arrays) is unlikely to resolve the underlying problems.

    Just my two cents.
    Now that I have your two cents (you are correct in your assessment...the code generates many warnings, etc., cannot be written very well at all...that is a given.), how is your post going to help with improving my code, speeding up the execution of my program?

  8. #8
    Sinecure devotee
    Join Date
    Aug 2013
    Location
    Southern Tier NY
    Posts
    5,911

    Re: is it a Variable or an Array?

    Quote Originally Posted by Bushranger View Post
    ..., how is your post going to help with improving my code, speeding up the execution of my program?
    If we can't see the code, we don't have much chance in improving the code, so what is left is to try to change your presumptions about what might benefit the unseen code.

    Usually, macro changes, i.e. better algorithms and practices, will have a much better chance of improving the process, rather than micro management of compiler based processes.

    If you can't give example code that will show how you are "mechanically" processing the data without exposing proprietary things that you don't want to reveal, then the perception on our end is that we are wasting our volunteered time on something that is not going to produce results, and that is a large incentive to not make the effort.

    Almost no-one wants to work on a pointless exercise. There is the slight chance that you will learn some things along the way, but the inefficiency of that type of transfer of knowledge is a real drag, so few will feel the drive to persevere alongside you.
    Last edited by passel; Jan 10th, 2020 at 04:07 PM.
    "Anyone can do any amount of work, provided it isn't the work he is supposed to be doing at that moment" Robert Benchley, 1930

  9. #9
    Fanatic Member
    Join Date
    Nov 2017
    Posts
    1,003

    Re: is it a Variable or an Array?

    passel said what I was going to say, worded much better than I could have.

    Basically, if you post code here, you will likely get really good feedback on what can be done to speed it up. If you don't want to post code because its your own encryption stuff that you want to keep secret, then your next best option is to post altered code that still performs the essence of what your actual code does.

    Lets say you have "scrambling" code and "assembling" code. The "scrambling" code is the code that turns the letter a into that lengthy number that you posted in the other thread. The "assembling" code is the code that takes all of the lengthy numbers that are generated from each letter of a message (assuming your encryption method is done character by character) and pieces them together to make the encrypted result. Maybe your slowness is in the assembling code (code that shouldn't be a problem to post since it won't reveal how the encryption is accomplished). Maybe you are doing multitudes of string concatenations to a String variable rather than using a StringBuilder object, and as that String gets longer and longer, the process slows down because of it.

    Or maybe you have a bunch of nested loops where, for each cycle through the outer loop, the inner loops loop exponentially more times or something like that.

    Those are all just guesses, which is the best I can offer without seeing code.

    Good luck.
    Last edited by OptionBase1; Jan 10th, 2020 at 04:38 PM.

  10. #10

    Thread Starter
    Lively Member
    Join Date
    Dec 2019
    Posts
    67

    Re: is it a Variable or an Array?

    Quote Originally Posted by OptionBase1 View Post
    passel said what I was going to say, worded much better than I could have.

    Basically, if you post code here, you will likely get really good feedback on what can be done to speed it up. If you don't want to post code because its your own encryption stuff that you want to keep secret, then your next best option is to post altered code that still performs the essence of what your actual code does.

    Lets say you have "scrambling" code and "assembling" code. The "scrambling" code is the code that turns the letter a into that lengthy number that you posted in the other thread. The "assembling" code is the code that takes all of the lengthy numbers that are generated from each letter of a message (assuming your encryption method is done character by character) and pieces them together to make the encrypted result. Maybe your slowness is in the assembling code (code that shouldn't be a problem to post since it won't reveal how the encryption is accomplished). Maybe you are doing multitudes of string concatenations to a String variable rather than using a StringBuilder object, and as that String gets longer and longer, the process slows down because of it.

    Or maybe you have a bunch of nested loops where, for each cycle through the outer loop, the inner loops loop exponentially more times or something like that.

    Those are all just guesses, which is the best I can offer without seeing code.

    Good luck.
    Actually, the program decodes the code at high speed and faultlessly. It is the code that encodes the text that is the problem. That is what makes it so frustrating.
    The problem with posting the code here, is there is so much of it, I don't know where to start...in the 3741 lines of code that encrypts the text. Nevertheless, I am going to start doing so upon your recommendation. Here is a preliminary of the entire process...not nearly all. I may post more later.

    Code:
    Imports System.IO
    Imports System.Threading
    
    Module Module1
        Friend NumbCounter As Integer = 1
        Dim Source As String
        Friend NumberOf As Integer = Len(Source)
        Friend CountOf As Integer = Len(strWholePathVar)
        Friend StrPadding(9) As Integer
        Public strWholePathVar As String          'should likly be "Friend" or "Privet", not "Public"?
        Public intPassWordLength As Integer
        Public filePath As String                  ' from Form5.TextBox2.Text
        Public Function AddPad() As Integer()
            Randomize()
            'Dim Strarray(9) As Integer
            Dim Strarray() As Integer 'dynamic array
            ReDim Strarray(9)
            Strarray(0) = CInt((Int(9 * Rnd())))
            Strarray(1) = CInt((Int(9 * Rnd()) + 1))
            Strarray(2) = CInt((Int(9 * Rnd())))
            Strarray(3) = CInt((Int(9 * Rnd())))
            Strarray(4) = CInt((Int(9 * Rnd())))
            Strarray(5) = CInt((Int(9 * Rnd())))
            Strarray(6) = CInt((Int(9 * Rnd())))
            Strarray(7) = CInt((Int(9 * Rnd())))
            Strarray(8) = CInt((Int(9 * Rnd())))
            Strarray(9) = CInt((Int(9 * Rnd()) + 1))
            Return Strarray
            'Release dynamic array memory 
            Erase Strarray
        End Function
        Public Function GetEven() As Integer
            Randomize()
            Dim Even As Integer
            Do Until ((Even Mod 2) = 0)
                Even = CInt(Int((9 * Rnd()) + 1)) ' The "+ 1" keeps from getting zeros.
            Loop
            Return Even
        End Function
        Public Function GetOdd() As Integer
            Randomize()
            Dim Odd As Integer
            Do Until ((Odd Mod 2) = 1)
                Odd = CInt(Int((9 * Rnd()) + 1))            ' The "+ 1" keeps from getting zeros.
            Loop
            Return Odd
        End Function
        Public Sub ToFile(ByVal StrPadding As Integer())
            Dim i As Integer
            'Writes the encrypted text to Form3, textbox2.
            For i = 0 To 9
                Form3.TextBox2.Text &= CStr(StrPadding(i))
            Next
        End Sub
        Public Function Encrypt(ByVal Source As String) As String
            'Finds the length of the string in Form3.TextBox1 combined with the length of the password, strPassWordVar.
            NumberOf = Len(Source)
            'Declares an Array of String-type data named PlainTextArray with NumberOf string data in it.
            'Dim PlainTextArray(NumberOf) As String
            Dim PlainTextArray() As String
            ReDim PlainTextArray(NumberOf)
            'Declares an Array of String-type data named AssignedNumArray with NumberOf string data in it.
            'Dim AssignedNumArray(NumberOf) As String
            Dim AssignedNumArray() As String
            ReDim AssignedNumArray(NumberOf)
            Dim IntCount As Integer
            ' **********************Initiates a parallel array for assigning numbers  ************
            For Increment = 1 To NumberOf
                'Puts contents of the text Box into an array, one character at a time.
                PlainTextArray(Increment) = Mid(Source, Increment, 1)
            Next
            'Change ASCII text to arbitrarily assigned double didget numbers via Select Case method.
            For Increment = 1 To NumberOf
                'Declares variable as string type.
                Dim InToCode As String
                Select Case PlainTextArray(Increment)
                    Case "a"
                        InToCode = "45"
                        AssignedNumArray(Increment) = InToCode
                    Case "b"
                        InToCode = "46"
                        AssignedNumArray(Increment) = InToCode
                    Case "c"
                        InToCode = "91"
                        AssignedNumArray(Increment) = InToCode
                    Case "d"
                        InToCode = "84"
                        AssignedNumArray(Increment) = InToCode
                    Case "e"

  11. #11

    Thread Starter
    Lively Member
    Join Date
    Dec 2019
    Posts
    67

    Re: is it a Variable or an Array?

    In regard to the Select Case statements above, there are case statements for 93 of the ASCII printable characters. Would I be possible, better off memory wise to convert the code to a Hash Table? Or, perhaps a Dictionary?
    Last edited by Bushranger; Jan 11th, 2020 at 12:31 PM. Reason: changed a term to "hash table."

  12. #12
    Fanatic Member
    Join Date
    Nov 2017
    Posts
    1,003

    Re: is it a Variable or an Array?

    The fact that you have 3741 lines of code in your encryption process is sort of a red flag right there. That seems excessive just from the standpoint of me wondering what is all going on in those lines of code.

    That being said, it should be somewhat clear that the code you've posted isn't doing any "heavy lifting", so it is difficult to provide significant useful feedback on what to do differently.

    I will note one thing though. In your GetEven and GetOdd functions, you are throwing away randomly generated values that, in the case of the GetEven function, are odd, and, in the case of the GetOdd function, are even; and then looping and choosing another random value.

    Since it isn't clear when/how often these functions are being called, that may not be a big deal.

    But, if you want to ensure generation of a random odd number, you can do just that. If you want a random odd integer from {1, 3, 5, 7, 9}, just generate a random integer of {0, 1, 2, 3, 4}, multiply by 2, and add 1.

    Similarly, if you want to ensure generation of a random even integer (non-zero), you would do the same as the odd integer generation, but add 2.

    Good luck.

  13. #13
    PowerPoster
    Join Date
    Sep 2005
    Location
    Modesto, Ca.
    Posts
    4,445

    Re: is it a Variable or an Array?

    I'm not an array or random number expert, never needed to use arrays much and I never needed a random number. I'm surprised more people haven't chimed in because there are lots of people here that are experts in using these things. Maybe because they've already viewed the post before you posted your code. But I do see a couple of things, don't know if they'll improve speed but here they are,

    Code:
            Dim PlainTextArray() As String
            ReDim PlainTextArray(NumberOf)
    
    Why two lines,
    
    Dim PlainTextArray(NumberOf) as String
    Randomize and Rnd are out of date, The .Net uses the Random Class. https://docs.microsoft.com/en-us/dot...tframework-4.8

    If you search this forum you will find a lot of information on using the Random Class. I also notice you are creating a new random generator everytime you want a number, I don't think that's necessary.

  14. #14

    Thread Starter
    Lively Member
    Join Date
    Dec 2019
    Posts
    67

    Re: is it a Variable or an Array?

    Quote Originally Posted by wes4dbt View Post
    I'm not an array or random number expert, never needed to use arrays much and I never needed a random number. I'm surprised more people haven't chimed in because there are lots of people here that are experts in using these things. Maybe because they've already viewed the post before you posted your code. But I do see a couple of things, don't know if they'll improve speed but here they are,

    Code:
            Dim PlainTextArray() As String
            ReDim PlainTextArray(NumberOf)
    
    Why two lines,
    
    Dim PlainTextArray(NumberOf) as String
    Randomize and Rnd are out of date, The .Net uses the Random Class. https://docs.microsoft.com/en-us/dot...tframework-4.8

    If you search this forum you will find a lot of information on using the Random Class. I also notice you are creating a new random generator everytime you want a number, I don't think that's necessary.
    There are two lines because as I understood it from the examples I found that for an array to be dynamic instead of static, there can be no argument in the parenthesis, and doing the Redim re-sizes the array to fit the current requirement. Is that not correct?

  15. #15
    PowerPoster
    Join Date
    Sep 2005
    Location
    Modesto, Ca.
    Posts
    4,445

    Re: is it a Variable or an Array?

    Should be easy to test,

    Code:
            Dim cnt = 3
            Dim arr(cnt) As String
    
            arr(0) = "a"
            arr(1) = "b"
            MessageBox.Show(arr.Length.ToString)
    
            ReDim arr(6)
    
            MessageBox.Show(arr.Length.ToString)

  16. #16

    Thread Starter
    Lively Member
    Join Date
    Dec 2019
    Posts
    67

    Re: is it a Variable or an Array?

    Quote Originally Posted by wes4dbt View Post
    I'm not an array or random number expert, never needed to use arrays much and I never needed a random number. I'm surprised more people haven't chimed in because there are lots of people here that are experts in using these things. Maybe because they've already viewed the post before you posted your code. But I do see a couple of things, don't know if they'll improve speed but here they are,

    Code:
            Dim PlainTextArray() As String
            ReDim PlainTextArray(NumberOf)
    
    Why two lines,
    
    Dim PlainTextArray(NumberOf) as String
    Randomize and Rnd are out of date, The .Net uses the Random Class. https://docs.microsoft.com/en-us/dot...tframework-4.8

    If you search this forum you will find a lot of information on using the Random Class. I also notice you are creating a new random generator everytime you want a number, I don't think that's necessary.
    You were right about doing a new random generator each time a randome number was called...I commented out the two after the first and the program ran correctly without them. thanks.

  17. #17
    Frenzied Member
    Join Date
    Jul 2011
    Location
    UK
    Posts
    1,282

    Re: is it a Variable or an Array?

    Quote Originally Posted by Bushranger View Post
    There are two lines because as I understood it from the examples I found that for an array to be dynamic instead of static, there can be no argument in the parenthesis, and doing the Redim re-sizes the array to fit the current requirement. Is that not correct?
    VB on the .NET platform doesn't have dynamic arrays.

    Using ReDim to resize an array just creates another new array in memory filled with the default values for the type of the array. The old array contents are no longer accessible, but they are still using up memory until .NET's garbage collector gets around to freeing up the memory.

    Using ReDim Preserve does pretty much the same, except the old contents of the array are copied over to the new array that is created.



    Quote Originally Posted by Bushranger View Post
    In regard to the Select Case statements above, there are case statements for 93 of the ASCII printable characters. Would I be possible, better off memory wise to convert the code to a Hash Table? Or, perhaps a Dictionary?
    In terms of code readability and maintenance, a lookup table of some sort would be much better than 93 Select Case statements.

    When it comes to memory usage, with just 93 two character values (and maybe a one character key) you're probably talking less than a KiloByte of memory, which is nothing.

    I think you're worrying way too much about memory usage. .NET does a pretty good job of memory housekeeping on its own.

    What makes you think you have memory problems anyway? Are you seeing OutOfMemory exceptions? Or does task manager's performance monitor show all your system's memory is being used when you run your program?

    From what I can tell, your code takes string data as input and spits out a much, much longer string. So I'm guessing you are performing a lot of string concatenation. As was pointed out in an one of your earlier threads, string concatenation in a big loop is a major cause of slowdown in code execution (while the loop is running). Hard to say without seeing more of your code.


    Quote Originally Posted by Bushranger View Post

    Code:
        Public Function GetEven() As Integer
            Randomize()
            Dim Even As Integer
            Do Until ((Even Mod 2) = 0)
                Even = CInt(Int((9 * Rnd()) + 1)) ' The "+ 1" keeps from getting zeros.
            Loop
            Return Even
        End Function
    I don't think that's doing what you think it is. Dim Even As Integer sets the value of Even to 0 (default value for Integers). Then in the next line, (Even Mod 2) = 0 is true so the do loop is never executed. The function will always return 0 .

  18. #18

    Thread Starter
    Lively Member
    Join Date
    Dec 2019
    Posts
    67

    Re: is it a Variable or an Array?

    What makes you think you have memory problems anyway? Are you seeing OutOfMemory exceptions?
    I think the memory is being loaded up due to the fact that the program starts out running fast but progressively slows down to a crawl (one short sentence took 2 min, 35 seconds to encrypt where as the same sentence was decrypted and displayed in a text box in less than a second). To my way of thinking, if variables were being add to as the program looped through, ran, etc. the program output would not be right. But, the program works as it should as evidenced by the correct text string that is produced when I run the decrypt part of the program. If it is not memory loading up, I don't know what else it could be.

  19. #19

    Thread Starter
    Lively Member
    Join Date
    Dec 2019
    Posts
    67

    Re: is it a Variable or an Array?

    I am going to work on the stuff a little at a time...here is one of my functions that I am told is obsolete, and that I should be using "Random Class" to generate random numbers and in this case, and odd random number between 1 and 9.
    Code:
      Public Function GetOdd() As Integer
            'Randomize()
            Dim Odd As Integer
            Do Until ((Odd Mod 2) = 1)
                Odd = CInt(Int((9 * Rnd()) + 1))            ' The "+ 1" keeps from getting zeros.
            Loop
            Return Odd
        End Function
    So, will this gain me anything..."If" it is correct for what I am trying to do?
    Code:
    Public Function GetOdd() As Integer
    		'Create an instance of the Random class
    		Dim rnd As New Random()
    		'Get an Even random number from 1 to 9
    		Dim randomNumber As Integer = rnd.Next(1, 10)
    		Odd = ((randomNumber)*2) + 1
    	 		Return Odd
       	 End Function

  20. #20
    PowerPoster
    Join Date
    Sep 2005
    Location
    Modesto, Ca.
    Posts
    4,445

    Re: is it a Variable or an Array?

    Like I said before I've never worked with random number but it's seems logical that if going to be creating random numbers in multiple functions/Subs that it would be faster to create it once with form/Module level scope then you can use it in anywhere in the form/module.

    Code:
    Module Module1
    
        Private rnd As New Random()
    
    Public Function GetOdd() As Integer
    		Dim Odd as Integer		
    		'Get an Even random number from 1 to 9
    		Dim randomNumber As Integer = rnd.Next(1, 10)
    		Odd = ((randomNumber)*2) + 1
    	 		Return Odd
       	 End Function
    
    End Module
    This is just a guess.
    Last edited by wes4dbt; Jan 12th, 2020 at 03:44 AM.

  21. #21
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    23,126

    Re: is it a Variable or an Array?

    Quote Originally Posted by wes4dbt View Post
    Like I said before I've never worked with random number but it's seems logical that if going to be creating random numbers in multiple functions/Subs that it would be faster to create it once with form/Module level scope then you can use it in anywhere in the form/module.

    Code:
    Module Module1
    
        Private rnd As New Random()
    
    Public Function GetOdd() As Integer
    				
    		'Get an Even random number from 1 to 9
    		Dim randomNumber As Integer = rnd.Next(1, 10)
    		Odd = ((randomNumber)*2) + 1
    	 		Return Odd
       	 End Function
    
    End Module
    This is just a guess.
    It's not just a case of speed. Declaring it once at Class or Module level initializes the Object once. If it were declared in the GetOdd() function and you called the function twice in quick succession, the chances are the Random Object would be seeded (it uses Environment.TickCount) with the same integer twice and therefore would give the same results...

  22. #22
    PowerPoster
    Join Date
    Sep 2005
    Location
    Modesto, Ca.
    Posts
    4,445

    Re: is it a Variable or an Array?

    Quote Originally Posted by .paul. View Post
    It's not just a case of speed. Declaring it once at Class or Module level initializes the Object once. If it were declared in the GetOdd() function and you called the function twice in quick succession, the chances are the Random Object would be seeded (it uses Environment.TickCount) with the same integer twice and therefore would give the same results...
    Finally someone who knows what their talking about, I was out of my comfort zone.

  23. #23

    Thread Starter
    Lively Member
    Join Date
    Dec 2019
    Posts
    67

    Re: is it a Variable or an Array?

    From what I can tell, your code takes string data as input and spits out a much, much longer string. So I'm guessing you are performing a lot of string concatenation. As was pointed out in an one of your earlier threads, string concatenation in a big loop is a major cause of slowdown in code execution (while the loop is running). Hard to say without seeing more of your code.
    Yes, for each character in the input string of text, there can be as many as 120 digits generated. However, after the first character is processed, those digits are written to a text box and the code should be good to go, just as with the first (few) characters. That should leave the code ready to process the next character without any more resources being used. I ran a test last night with a long paragraph of about four sentences...it took nearly an hour to process into the text box. The key it would seem to me is that the slowdown is obviously progressive....just like the memory resources are being used up. However, that long text string processing did not result in any kind of stoppage or error message. And when I ran decrypt on the file that was finished and written to the hard drive, it decrypt the text almost instantly. The decrypt is different than the encrypting in that it uses two very long Select Case processes but no randomizing...so if the problem is not excess memory usage, it must have something to do with the randomizing or the calls to functions. It has me stymied for sure, but I am going to continue to make adjustments (improvements) to the code until I find it.

  24. #24
    Fanatic Member
    Join Date
    Nov 2017
    Posts
    1,003

    Re: is it a Variable or an Array?

    Quote Originally Posted by Bushranger View Post
    Yes, for each character in the input string of text, there can be as many as 120 digits generated. However, after the first character is processed, those digits are written to a text box and the code should be good to go, just as with the first (few) characters. That should leave the code ready to process the next character without any more resources being used. I ran a test last night with a long paragraph of about four sentences...it took nearly an hour to process into the text box.
    So your code is continuously writing the encrypted results "piecemeal" to a textbox from the go? That is very inefficient. If your code is doing ANYTHING with a UI element (textbox, label, button, listbox, etc.) repeatedly inside of your encryption routine, that is a performance problem.

    You should be creating a StringBuilder object that you use to store the encrypted results, and update that StringBuilder as needed. Then, after your encryption routine is finished, update the textbox with the contents of the StringBuilder object.

    I mentioned this before, but if you are using plain "String" variables, and doing something like:

    Code:
    strVariable = strVariable & strToAppend
    Then you should be using a StringBuilder object rather than a String.

    Read this thread for reference. It has performance testing and graphs that illustrate how much slower String concatenation is vs. using a StringBuilder.

    http://www.vbforums.com/showthread.p...-Concatenation

    Good luck.

  25. #25

    Thread Starter
    Lively Member
    Join Date
    Dec 2019
    Posts
    67

    Re: is it a Variable or an Array?

    I don't think that's doing what you think it is. Dim Even As Integer sets the value of Even to 0 (default value for Integers). Then in the next line, (Even Mod 2) = 0 is true so the do loop is never executed. The function will always return 0 .
    I set a watch to see what happens when the program runs, and you are correct. The "Even" is always zero. However the program coding still works inasmuch as evidently the program is interpreting a zero as an even number. I doubt if I would have ever caught that on my own...thanks for pointing that out.

    I "fixed" the problem by setting the Var "Even" to 3...an odd number after the I did a watch on the variable and it did give me random (or seemingly so) numbers from one to nine instead of the constant zeros.
    Code:
    Public Function GetEven() As Integer
            Randomize()
            Dim Even As Integer
            Even = 3
            Do Until ((Even Mod 2) = 0)
                Even = CInt(Int((9 * Rnd()) + 1)) ' The "+ 1" keeps from getting zeros.
            Loop
            Return Even
        End Function
    Not likely elegant or correct, but it does give me the result I wanted.
    Last edited by Bushranger; Jan 13th, 2020 at 11:38 PM.

  26. #26
    PowerPoster
    Join Date
    Sep 2005
    Location
    Modesto, Ca.
    Posts
    4,445

    Re: is it a Variable or an Array?

    Just to be clear, each character of encrypted text has it's own separate text string. There is never any concatenation of the individual encrypted character strings during encryption.

  27. #27
    PowerPoster techgnome's Avatar
    Join Date
    May 2002
    Posts
    32,795

    Re: is it a Variable or an Array?

    Quote Originally Posted by Bushranger View Post
    I set a watch to see what happens when the program runs, and you are correct. The "Even" is always zero. However the program coding still works inasmuch as evidently the program is interpreting a zero as an even number. I doubt if I would have ever caught that on my own...thanks for pointing that out.

    I "fixed" the problem by setting the Var "Even" to 3...an odd number after the I did a watch on the variable and it did give me random (or seemingly so) numbers from one to nine instead of the constant zeros.
    Code:
    Public Function GetEven() As Integer
            Randomize()
            Dim Even As Integer
            Even = 3
            Do Until ((Even Mod 2) = 0)
                Even = CInt(Int((9 * Rnd()) + 1)) ' The "+ 1" keeps from getting zeros.
            Loop
            Return Even
        End Function
    Not likely elegant or correct, but it does give me the result I wanted.
    Don't forget to change the Rnd() to rnd.getNext() and drop the Randomize() call ... make it inline with your Odd function.

    On a related note... GetOdd and GetEven are virtually the same, the only difference is the result you look for in the mod calculation.... just saying... if you want to condense code and reduce some of it... you could.

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Featured


Click Here to Expand Forum to Full Width