Search code examples
c#performancealgorithmwords

Working on one word, dilemma using string or char array or stringbuilder?


I am working on a chess(not grid). This chess(not grid) has X rows.
In each of rows we have Y blocks.

I would like to know what words can I find in each of the rows. Also what is that's words start and stop indexes.

So my tactic for one row is:

  • take all items from row (-cat--dog----) and save it to string
  • operate on string's indexes using for(...){...}

Is it good idea or maybe I should convert that string to char array and then operate?

What method is faster to do that? What about StringBuilder?

@Oden thx for correction but I didn't mean grid but just a chess :)


Somewhere I wrote this question wrong. (Maybe I wrong formulated the question. It's hard to make this shape for me, so sorry.)

The main problem's question was simply included in main title of this topic.
What method would be faster while processing over words for example mamma--mia (each element is ansi symbol, let say in string format)?

So I wonder if I were working on just a string it would be faster than first converting string toCharArray and work then. Or maybe using stringBuilder.

I simply ask what is faster: work or chars, strings or elements of string builder in my method.. :( What would be faster in big function/method -> that's the question.


Solution

  • The performance bottleneck you're facing is not in the string construction, but in finding the words you're looking for. If you have m words you're looking for, you might end up going through the string looking for words m times. That's not necessary! You might try and create a huge regular expression * matching all substrings you're looking for. The way they are constructed *, they only pass the string once (basically if you start with an 'a', they're in a state that tells them "this could be a beginning to all the words beginning with a", if the next char is a 'b', state says "this could either be the beginning of a word starting with ab or the beginning of a word starting with b).