[Gambas-user] convert string to collection
Bruce Steers
bsteers4 at gmail.com
Thu May 4 11:38:58 CEST 2023
On Thu, 4 May 2023 at 06:07, Mayost Sharon <sharon at 455.co.il> wrote:
> ---------- Original Message -----------
> From: Jussi Lahtinen <jussi.lahtinen at gmail.com>
> To: Gambas Mailing List <user at lists.gambas-basic.org>
> Sent: Thu, 4 May 2023 01:29:36 +0300
> Subject: Re: [Gambas-user] convert string to collection
>
> > Lee already showed the shorter way, but did you mean faster..?
> >
> > Jussi
> >
> > On Wed, May 3, 2023 at 7:06 PM Mayost Sharon <sharon at 455.co.il> wrote:
> >
> > > I want to convert the string to a collection
> > >
> > > The way I did it is:
> > >
> > > Public Sub Main()
> > > Dim col_01 As New Collection
> > > Dim ar_s_01 As String[]
> > > Dim s_01 As String
> > > Dim s_02 As String
> > >
> > > s_01 = "Event: Hangup\nPrivilege: call, all\nChannel: SIP / 4
> F2060EB4 -
> > > 00000000\nUniqueid: 1283174108.0\nCallerIDNum:
> 2565551212\nCallerIDName:
> > > Russell Bryant\nCause: 16\nCause - txt: Normal Clearing"
> > >
> > > ar_s_01 = Split(s_01, Chr(10))
> > >
> > > For Each s_02 In ar_s_01
> > > col_01.Add(Trim(Split(s_02, ":")[1]), Trim(Split(s_02, ":")[0]))
> > > Next
> > >
> > > Print col_01["Event"]
> > > Print col_01["Privilege"]
> > > Print col_01["Uniqueid"]
> > > Stop
> > > End
> > >
> > > Is this the right way?
> > > Or is there a shorter way to do it?
> > >
> > > Thank you
> > >
> > > ----[ http://gambaswiki.org/wiki/doc/netiquette ]----
> > >
> ------- End of Original Message -------
>
> Yes
> I meant it to be faster too
>
> According to what Lee showed
> Will it work slower?
> why?
>
> Thank you
>
3 ways to speed it up...
Only use Split to Split the string once then use the vars. Using Split
twice is slower.
do not use Trim on var[0] as it is not needed.
use LTrim as this will only test the left part of the string.
Dim aSplit As String[]
For Each s_02 In Split(s_01, Chr(10))
aSplit = Split(s_02, ":")
col_01.Add(LTrim(aSplit[1]), aSplit[0])
Next
Or maybe it is faster using Mid...
Dim iPos As Integer
For Each s_02 In Split(s_01, Chr(10))
iPos = InStr(s_02, ": ")
col_01.Add(Mid(s_02, iPos + 2)), Mid(s_02, 1, iPos - 1))
Next
I am not sure what is the fastest.
You can test speed yourself.
Make a For/Next loop that runs the method 100 times
activate the profiler (menu Debug/Activate profiling)
Press "run", let the code complete then close the program and see the
results of your method.
BruceS
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.gambas-basic.org/pipermail/user/attachments/20230504/395ed89c/attachment.htm>
More information about the User
mailing list