Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8691425
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T00:07:10+00:00 2026-06-13T00:07:10+00:00

string s = abcabcabcabcabc; var foundIndexes = new List<int>(); The question came from the

  • 0
string s = "abcabcabcabcabc";

var foundIndexes = new List<int>();

The question came from the discussion here. I was simply wondering

How can this:

for (int i = s.IndexOf('a'); i > -1; i = s.IndexOf('a', i + 1))  

      foundIndexes.Add(i); 

Be better than this :

for (int i = 0; i < s.Length; i++)

      if (s[i] == 'a') foundIndexes.Add(i);

EDIT : Where all does the performance gain come from?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-13T00:07:11+00:00Added an answer on June 13, 2026 at 12:07 am

    I did not observe that using IndexOf was any faster than direct looping. Honestly, I don’t see how it could be because each character needs to be checked in both cases. My initial results were this:

    Found by loop, 974 ms 
    Found by IndexOf 1144 ms
    

    Edit: After running several more times I’ve noticed that you must run release (ie with optimizations) to see my result above. Without optimizations, the for loop is indeed slower.

    The benchmark code:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text.RegularExpressions;
    using System.Text;
    using System.IO;
    using System.Diagnostics;
    
    namespace Test
    {
        public class Program
        {
            public static void Main(string[] args)
            {
                const string target = "abbbdbsdbsbbdbsabdbsabaababababafhdfhffadfd";
    
                // Jit methods
                TimeMethod(FoundIndexesLoop, target, 1);
                TimeMethod(FoundIndexesIndexOf, target, 1);            
    
                Console.WriteLine("Found by loop, {0} ms", TimeMethod(FoundIndexesLoop, target, 2000000));
                Console.WriteLine("Found by IndexOf {0} ms", TimeMethod(FoundIndexesIndexOf, target, 2000000));           
            }
    
            private static long TimeMethod(Func<string, List<int>> method, string input, int reps)
            {
                var stopwatch = Stopwatch.StartNew();
                List<int> result = null;
                for(int i = 0; i < reps; i++)
                {
                    result = method(input);
                }
                stopwatch.Stop();
                TextWriter.Null.Write(result);
                return stopwatch.ElapsedMilliseconds;
            }
    
            private static List<int> FoundIndexesIndexOf(string s)
            {
                List<int> indexes = new List<int>();
    
                for (int i = s.IndexOf('a'); i > -1; i = s.IndexOf('a', i + 1))
                {
                     // for loop end when i=-1 ('a' not found)
                    indexes.Add(i);
                }
    
                return indexes;
            }
    
            private static List<int> FoundIndexesLoop(string s)
            {
                var indexes = new List<int>();
                for (int i = 0; i < s.Length; i++)
                {
                    if (s[i] == 'a')
                    indexes.Add(i);
                }
    
                return indexes;
            }
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

string tags = 9,3,12,43,2 List<int> TagIds = tags.Split(','); This doesn't work cause the split
string str = Select bd_id from [Active]; ds = new DataSet(str); da = new
String query = select email from emp_select; Statement stmt; try { DB db=new DB();
string sequence = 12345; int[] ziffern = new int[sequence.Count()]; for (int i = 0;
String input from keyboard Vector<String> myVector = new Vector<String>(someArray.length); //assume Vector is populated Iterator<String>
string[] filesOfType1 = GetFileList1(); string[] filesOfType2 = GetFileList2(); var cookieMap = new Dictionary<string, CookieContainer>();
String[] names=new String[4]; int[] scores=new int[4]; Scanner keyboard = new Scanner(System.in); System.out.println(Enter 4 strings
string in question: '{images:{0:<div style=\\background:red;width:250px;height:250px;display:block;position:absolute;\\></div>}}' I've tried various combinations of single and double quotes.
string abc = 07:00 - 19:00 x = int.Parse(only first two characters) // should
string[] strArray = new string[10] { 21.65, 30.90, 20.42, 10.00, 14.87, 72.19, 36.00, 45.11,

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.