fast custom string splitting

后端 未结 3 977
离开以前
离开以前 2021-01-06 17:25

I am writing a custom string split. It will split on a dot(.) that is not preceded by an odd number of backslashes (\\).

«string» -         


        
3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-06 18:18

    The loop that you show is the right approach if you need performance. (Regex wouldn't be).

    Switch to an index-based for-loop. Remember the index of the start of the match. Don't append individual chars. Instead, remember the range of characters to copy out and do that with a single Substring call per item.

    Also, don't use a LinkedList. It is slower than a List for almost all cases except random-access mutations.

    You might also switch from List to a normal array that you resize with Array.Resize. This results in slightly tedious code (because you have inlined a part of the List class into your method) but it cuts out some small overheads.

    Next, don't return an IEnumerable because that forces the caller through indirection when accessing its items. Return a List or an array.

提交回复
热议问题