How can I optimize this code snippet?
string page = wc.DownloadString("https://www.youtube.com/browse_ajax?action_continuation=1&continuation=4qmFsgI8EhhVQ2ZXdHFQeUJNR183aTMzT2VlTnNaWncaIEVnWjJhV1JsYjNNZ0FEQUJPQUZnQVdvQWVnRTB1QUVB");
int pos;
while ((pos = page.IndexOf("/watch?v=")) > 0) {
page = page.Substring(pos);
page = page.Substring(page.IndexOf("video-time"));
page = page.Substring(page.IndexOf("aria-label"));
page = page.Substring(page.IndexOf(@"\u003e") + 6);
string vt = page.Substring(0, page.IndexOf(@"\u003c"));
page = page.Substring(page.IndexOf("title=") + 1);
page = page.Substring(page.IndexOf("title=") + 1);
page = page.Substring(page.IndexOf("title=") + 1);
page = page.Substring(page.IndexOf("\\\"") + 2);
string tt = page.Substring(0, page.IndexOf("\\\" aria-describedby="));
}
Sadly, I can't just skip some of the Substring
lines as this seems to be the only way to find the right occurance of vt
and tt
.
Since Substring
always returns a new string I tried a solution with StringBuilder
:
System.Text.StringBuilder sb=new System.Text.StringBuilder(wc.DownloadString("https://www.youtube.com/browse_ajax?action_continuation=1&continuation=4qmFsgI8EhhVQ2ZXdHFQeUJNR183aTMzT2VlTnNaWncaIEVnWjJhV1JsYjNNZ0FEQUJPQUZnQVdvQWVnRTB1QUVB"));
int pos;
while ((pos = sb.ToString().IndexOf("/watch?v=")) > 0) {
sb.Remove(0,pos);
sb.Remove(0,sb.ToString().IndexOf("video-time"));
sb.Remove(0,sb.ToString().IndexOf("aria-label"));
sb.Remove(0,sb.ToString().IndexOf(@"\u003e") + 6);
string vt =sb.ToString(0,sb.ToString().IndexOf(@"\u003c"));
sb.Remove(0,sb.ToString().IndexOf("title=") + 1);
sb.Remove(0,sb.ToString().IndexOf("title=") + 1);
sb.Remove(0,sb.ToString().IndexOf("title=") + 1);
sb.Remove(0,sb.ToString().IndexOf("\\\"") + 2);
string tt =sb.ToString(0,sb.ToString().IndexOf("\\\" aria-describedby="));
}
I was suprised to find out that this solution, although it doesn't look like due to all the ToString()
, is indeed slightly faster.
Now, is there a way to optimize this even further? Maybe even make it look better?