Fastest way to read specific line from string
I'm working on a project that involves reading specific lines of a file multiple times. I'm afraid this ReadLine function is the reason it takes a painfully long time to finish so I'm trying to optimize it, but I'm not sure what is the fastest way to do it
This was my old code:
This is my new code: (prevText is in place in case it reads the same thing so that it skips splitting it)
5 Replies
Firstly this
Instance
thing looks... very concerning
I don't know why you're using static fields instead of local variables
Anyway, you could just loop through the entire string, incrementing the line number on every newline character, then when you get to the target line just slice the string until the next newline.it is pretty concerning but works for now
would that be more efficient?
Well it wouldn't be allocating the array
So... maybe
Benchmark it if you really need to
But god, please get rid of this static/non-static nonsense.
Unless you store all of the text in code and cache each line, there isn't really any other way to optimise
A text editor for something like an IDE store all characters ofc, but also the character index of specific control characters like new line chars, which get updated when the original text changes. So maybe could you create something like that?
Suggestion: don't create a string[]. Instead create an int[] where each element indicates the offset of the next '\n'. The first element implicitly starts and 0, then use IndexOf until you reach the end of the text. You can then use the n and n-1 indices to get the span of the string and only create the new string (Substring) if it is needed. You could also "lazily" evaluate the indices as needed, meaning if they ask for the first line there is no reason to calculate the indices of every line in the file, you can stop after you get to the requested index, and resume from there if they request again.
Hard to make suggestions without understanding the expected access/usage patterns though.