What is the faster way of trying to find a single character on a String?

What of this code is faster/more efficient? :

Boolean contains = myString.IndexOf("~", StringComparision.InvariantCultureIgnoreCase)!=-1;


Boolean contains = myString.IndexOf('~')!=-1;

I think the second because is a single character, but using the invariant culture ignore case comparer is supposed to be fast too :P


-------------Problems Reply------------

The second one is a lot faster. On my machine it take about 340ms to do the first and 34ms to do the second one. So 10 times.

Interestingly using InvariantCulture as opposed to InvariantCultureIgnoreCase is faster and as Guffa pointed out Oridinal is faster still. But not as fast as IndexOf(char) though.

static void Main(string[] args)
string myString = "qwertyuipasdfghjklzxcvbnm,.~";

var s = Stopwatch.StartNew();

for (int i = 0; i < 1000000; i++)
Boolean contains = myString.IndexOf("~", StringComparison.InvariantCultureIgnoreCase) != -1;


var s2 = Stopwatch.StartNew();

for (int i = 0; i < 1000000; i++)
Boolean contains = myString.IndexOf('~') != -1;



The invariant culture is faster than other cultures, but ordinal comparison is even faster. Making it case insensetive is slower for these settings. So the fastest string comparison setting is StringComparison.Ordinal.

Searching for a character is about twice as fast as the fastest string search.

the two snippets are not equivalent, use whichever is correct. if you are having performance issues profile.

Write your own microbenchmark. Time the running of 100000 times of each of these. That should give you the answer.

You also can take a look here Optimizing string operations in C#, maybe this also will give you some ideas, of how you can optimize it for your needs.

For what it's worth, the IndexOf(char) overload will be significantly faster, but you probably won't notice unless you're doing tens-of-thousands-to-millions of these comparisons.

You should use whichever overload is most appropriate for what you're actually trying to do.

If you need a culture-aware and/or case-insensitive comparision then use the appropriate IndexOf overload and StringComparison option. In this situation, where you're just searching for the ~ character then it makes most sense to simply use IndexOf('~').

Category:c# Views:0 Time:2010-05-27
Tags: .net c# string

Related post

  • Is there a faster way to download a page from the net to a string? 2010-06-16

    I have tried other methods to download info from a URL, but needed a faster one. I need to download and parse about 250 separate pages, and would like the app to not appear ridiculously slow. This is the code I am currently using to retrieve a single

  • Faster/Easier way to compare an NSString to a bunch of strings 2010-10-14

    Is there a better way in Objective-C to do: if ([elementName isEqual:@"one"]){ // do some stuff } else if ([elementName isEqual:@"two"]]{ // do more stuff } else if ([elementName isEqual:@"three"]]{ // do more stuff } ideally, I would like something

  • Can this mySQL query be faster? 2011-09-01

    With this I check if there is already a member registered with the same login. My concern is if the database grows bigger to thousands of members, should I edit this somehow ? $qry = "SELECT * FROM registered WHERE login='$login'"; $result = mysql_qu

  • RegEx to tell if a string does not contain a specific character 2008-10-13

    Easy question this time. I'm trying to test whether or not a string does not contain a character using regular expressions. I thought the expression was of the form "[^x]" where x is the character that you don't want to appear, but that doesn't seem

  • Repeat String - Javascript 2008-10-14

    What is the best or most concise method for returning a string repeated an arbitrary amount of times? The following is my best shot so far: function repeat(s, n){ var a = []; while(a.length < n){ a.push(s); } return a.join(''); } --------------Sol

  • How would you count occurrences of a string within a string? 2009-02-12

    I am doing something where I realised I wanted to count how many /s I could find in a string, and then it struck me, that there were about several ways to do it, but couldn't decide on what the best (or easiest) was. At the moment I'm going with some

  • LEN function not including trailing spaces in SQL Server 2010-01-08

    I have the following test table in SQL Server 2005: CREATE TABLE [dbo].[TestTable] ( [ID] [int] NOT NULL, [TestField] [varchar](100) NOT NULL ) Populated with: INSERT INTO TestTable (ID, TestField) VALUES (1, 'A value'); -- Len = 7 INSERT INTO TestTa

  • What's the difference between tr/// and s/// when using regex in Perl? 2010-09-03

    I was wondering when one should use s/// over tr/// when working with regular expressions in Perl? --------------Solutions------------- s/// is for substitution: $string =~ s/abc/123/; This will replace the first "abc" found in $string with "123". tr

  • How to get the number of differences in a string comparison? 2010-10-11

    I know I can get whether 2 strings are equal in content, but I need to be able to get the number of characters that differ in the result of comparing 2 string values. For instance: "aaaBaaaCaaaDaaaEaaa" "aaaXaaaYaaaZaaaEaaa" so the asnwer is 3 for th

  • Decimal from a char* to binary 2012-01-30

    I have a string that consists some decimal value, with number of digits can be more than any existing int-types can hold(I know the number of digits). Give me some hints, please, how can I convert that number to it's binary representation (so I will

  • Numeric value of string and vice versa in perl 2012-04-23

    Is there any built in function (like we have ord for single character) to convert string into its equivalent numeric value and vice versa i.e. getting back the string from the equivalent numeric value.Please help,I need it urgently. --------------Sol

  • Building a string with chars 2013-11-13

    I've written a sort of stream class that read a FASTA file sequence by sequence: Interface: class Sequence_stream{ public: Sequence_stream(const char* Filename, std::string Format); // Constructor. NucleotideSequence get(); // Get a sequence from fil

  • C++ Which is faster: Stack allocation or Heap allocation 2008-10-02

    This question may sound fairly elementary, but this is a debate I had with another developer I work with. I was taking care to stack allocate things where I could, instead of heap allocating them. He was talking to me and watching over my shoulder an

  • vbscript optimization : how to get faster file writing 2009-01-27

    The following is the usual log function I utilize in alot of my vbscripts which I modify accordingly. I feel it writes too slow. I got 3 questions: Any ideaas on how to optimize this so it writes faster? Would it be faster to store all text in a stri

  • Does any one know of a faster method to do String.Split()? 2009-02-20

    I am reading each line of a CSV file and need to get the individual values in each column. So right now I am just using: values = line.Split(delimiter); where line is the a string that holds the values that are seperated by the delimiter. Measuring t

  • Is it faster to search for a large string in a DB by its hashcode? 2009-03-18

    If I need to retrieve a large string from a DB, Is it faster to search for it using the string itself or would I gain by hashing the string and storing the hash in the DB as well and then search based on that? If yes what hash algorithm should I use

  • Faster way to populate with Javascript 2009-03-30

    I have two <select> boxes on a form. Selecting an item in the first <select> box will determine what should appear in the second <select> (Using Ajax http_request). In some cases there can be a large 500 (guess) items in the second

  • Fast implementation of Rolling hash 2009-04-02

    I need a Rolling hash to search for patterns in a file. (I am trying to use the rabin-Karp string search algorithm). I understand how a good hash works and how a good rolling hash should work but I am unable to figure out how to efficiently implement

  • unique integer/long hash key generation over strings for faster compairson 2009-07-02

    I'm curious how others have solved this problem, and what problems might lurk behind the naive solution: I have a system which processes stock market data. There are tens of thousands of symbols, with associated prices/sizes, flowing into the system

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.168 (s). 11 q(s)