Char Count Speed Test (vb.net)

A few months ago i posted the below post on a different blog. Since this is my dedicated programming blog, I thought I’d bring it over here. I commonly need to return the number of a specific character in a string, and was never really happy with what i found on the internet. Here are some concepts of different ways to do it.

Function cnt_occ1(ByRef sIn As String, ByRef sFor As String, Optional ByVal casesensitive As Boolean = False) As Integer
Dim startTime As DateTime = DateTime.Now
Dim ts As String = “”
If casesensitive Then
ts = sIn.Replace(sFor, “”)
Else
ts = sIn.Replace(sFor.ToUpper, “”).Replace(sFor.ToLower, “”)
End If
Dim executionTime As TimeSpan = DateTime.Now – startTime
MsgBox(executionTime.Seconds.ToString() & “:” & executionTime.Milliseconds.ToString())
Return sIn.Length – ts.Length
End Function

Function cnt_occ2(ByRef OrigString As String, ByVal Chars As String, Optional ByVal CaseSensitive As Boolean = False) As Integer
Dim startTime As DateTime = DateTime.Now
http://www.freevbcode.com/ShowCode.Asp?ID=1025
Dim lLen As Long
Dim lCharLen As Long
Dim lAns As Long
Dim sInput As String
Dim sChar As String
Dim lCtr As Long
Dim lEndOfLoop As Long
Dim bytCompareType As Byte

sInput = OrigString
If sInput = “” Then Return 0
lLen = Len(sInput)
lCharLen = Len(Chars)
lEndOfLoop = (lLen – lCharLen) + 1
bytCompareType = IIf(CaseSensitive, vbBinaryCompare, _
vbTextCompare)

For lCtr = 1 To lEndOfLoop
sChar = Mid(sInput, lCtr, lCharLen)
If StrComp(sChar, Chars, bytCompareType) = 0 Then lAns = lAns + 1
Next
Dim executionTime As TimeSpan = DateTime.Now – startTime
MsgBox(executionTime.Seconds.ToString() & “:” & executionTime.Milliseconds.ToString())
Return lAns
End Function

Function cnt_occ3(ByRef sIn As String, ByRef sFor As String, Optional ByVal casesensitive As Boolean = False) As Integer
Dim startTime As DateTime = DateTime.Now
Dim oc As Integer
Dim pos As Integer
Dim ts As String = “”
Dim lp As Integer
If casesensitive = False Then
ts = sIn.ToLower
sFor = sFor.ToLower
lp = ts.LastIndexOf(sFor)
Else
lp = sIn.LastIndexOf(sFor)
ts = sIn
End If

While 1 = 1
oc += 1
pos = ts.IndexOf(sFor, pos) + 1
If pos >= lp Then
Exit While
End If
End While
Dim executionTime As TimeSpan = DateTime.Now – startTime
MsgBox(executionTime.Seconds.ToString() & “:” & executionTime.Milliseconds.ToString())
Return oc
End Function

Function cnt_occ4(ByRef sIn As String, ByRef sFor As String, Optional ByVal casesensitive As Boolean = False) As Integer
Dim startTime As DateTime = DateTime.Now
Dim oc As Integer

Dim ts As String = “”
If casesensitive = False Then
ts = sIn.ToLower
sFor = sFor.ToLower
Else
ts = sIn
End If
While 1 = 1
oc += 1
ts = ts.Substring(ts.IndexOf(sFor) + 1)
If ts.IndexOf(sFor) = -1 Then
Exit While
End If
End While
Dim executionTime As TimeSpan = DateTime.Now – startTime
MsgBox(executionTime.Seconds.ToString() & “:” & executionTime.Milliseconds.ToString())
Return oc
End Function

I thought that to count the occurrences of a character in a string I could replace it with nothing, then diff the lengths. Indeed it is faster. Surprisingly the 2nd fastest is looping through each character. Next we have the index of the string saved and looking for the next index of. Lastly we have the string cut for each occurrence.

Here’s the results:
Small number of occurrences-
1-0.46
2-0.93
3-0.812
4-5.640

Large number of occurrences-
1-0.31
2-0.93
3-4.843
4-34.508

key:
seconds.milliseconds

conclusion:
My code is not only always faster but it’s also much cleaner and readable. I’m sure someone else has done this but I hadn’t read about it before.

The code can then be reduced to:

Function cnt_occ(ByRef sIn As String, ByRef sFor As String, Optional ByVal casesensitive As Boolean = False) As Integer
If casesensitive Then
Return sIn.Length – sIn.Replace(sFor, “”).Length
Else
Return sIn.Length – sIn.Replace(sFor.ToUpper, “”).Replace(sFor.ToLower, “”).Length
End If
End Function

  1. With illegal immigration an even bigger, and more contentious,
    challenge lately, the country has tightened up the procedure to develop into a
    lawful permanent resident.

  2. Hey nice post. I hope it’s ok that I shared this on my FB, if not, no problem
    just tell me and I’ll delete it. Regardless keep up the great work.

  3. Very quickly this website will be famous amid all blogging users, due to
    it’s good posts

  4. I blog often and I really thank you for your content.
    This article has truly peaked my interest. I’m going to
    book mark your website and keep checking for new information about once per week.
    I subscribed to your Feed too.

  5. Simply wish to say your article is as amazing. The clarity
    on your put up is just great and i could assume you’re an expert in this subject.
    Well together with your permission allow me to clutch your feed to stay up to date with coming near near post.

    Thanks a million and please carry on the enjoyable work.

  6. Dr. David Rempel says that if you use a keyboard far more than 10
    hours a week and already knowledge this discomfort or discomfort, you must contemplate an ergonomic keyboard.

  7. Über die Geschichte dieser britischen Plastischen
    Chirurgie ja sogar des Verbandes solcher „BAPS British
    Association of Plastic Surgeons“ indem der
    beiden Weltkriege weiterhin der Hiatus wird
    in welcher vonseiten Wallace, „Honorary Archivist to the
    Association“ herausgegebenen Vierzigjahresfestschrift
    durch vielen Feinheiten berichtet (Wallace
    1987).
    Zur gleichen Zeit gleich Ganzer (1879–1960)
    in Berlin erbrachte Kazanjian in Etaples nahe
    Boulogne nicht zuletzt den Frontlinien den wichtigen
    Beitrag welcher prothetischen Zahnheilkunde pro
    die Erstbehandlung dieser Schusswunden des Gesichtes.
    Kazanjian war als Zahnchirurg Mitglied
    dieser „First Harvard Unit Attached to the British
    Expeditionary Force“ (Kazanjian and Converse
    1949).1920 kehrte er in die Amerika zurück, trat in
    die „Harvard Medical School“ ein darüber hinaus wurde
    „einer welcher führenden Plastischen Chirurgen solcher
    Welt“ (Converse 1977).
    Dies plastisch-chirurgische Methode
    in Tempus der „Adoleszenz
    des Weiteren des Wachstums“ 1918–1939
    Andere wichtige Feinheiten der Dynamik
    des Konzeptes der Plastischen Chirurgie in den
    USA nebst hinauf internationaler Ebene bis zum Ende
    145 4
    4.1 • Die neue Wissenschaft – Mann, Gillies, Converse

  8. It’s amazing in favor of me to have a web page, which is useful in support of my knowledge.
    thanks admin

  9. The next time I read a blog, I hope that it won’t fail me as
    much as this particular one. I mean, Yes, it was my choice to read, however I genuinely believed you
    would probably have something helpful to say. All I hear is a bunch of moaning about something that you could possibly fix if
    you weren’t too busy looking for attention.

  10. Hello everyone, it’s my first pay a visit at this web page,
    and post is truly fruitful in favor of me,
    keep up posting these content.

  11. An outstanding share! I’ve just forwarded this onto a friend who had been conducting a little homework on this.
    And he in fact ordered me breakfast due to the fact that I found it for him…
    lol. So let me reword this…. Thank YOU for the meal!!
    But yeah, thanx for spending the time to discuss this subject here on your internet site.

  12. Hello, the whole thing is going well here and ofcourse every one is sharing information, that’s
    in fact good, keep up writing.

  13. Hi there to all, how is the whole thing, I think every one is getting more from this site, and your views are pleasant for new viewers.

  14. Hello colleagues, its wonderful piece of writing concerning tutoringand fully explained,
    keep it up all the time.

  15. There are numerous possibilities to get actual free gem hack
    for Conflict of Clans no survey, but when you don’t examine it properly,
    you’ll only get the tail.

  16. You are so awesome! I do not think I’ve truly read through anything like that
    before. So good to find someone with a few unique thoughts
    on this subject matter. Really.. many thanks for starting this up.
    This website is something that is required on the internet, someone
    with a bit of originality!

  17. After I initially left a comment I seem to have clicked on the -Notify me
    when new comments are added- checkbox and now whenever a comment is added I receive 4 emails
    with the same comment. Perhaps there is a means you can remove me from that service?
    Kudos!

  1. February 9th, 2017
    Trackback from : Related Site
  2. February 27th, 2017
    Trackback from : cree cicchino siblings
  3. March 22nd, 2017
  4. March 25th, 2017
    Trackback from : Adidas Tubular Womens
  5. March 25th, 2017
    Trackback from : Yeezy Boost 750
  6. April 20th, 2017
    Trackback from : Texans J.J. Watt Mens Jersey
  7. April 20th, 2017
    Trackback from : can ho cao cap
  8. May 14th, 2017
    Trackback from : גרפיקאי בקריות
  9. May 18th, 2017
    Trackback from : estate everything youre
Comments are closed.
%d bloggers like this: