Skip to main content

ToLower - optimization

Mai mult ca sigur stiti ce face metoda ToLower( cand vreti sa transformati un string, pentru a avea toate caracterele mici este nevoie sa apelam la aceasta metoda).
Daca ne uitam peste definitie, o sa observam ca exista 3 variante
  • ToLower()
  • ToLowerInvariant()
  • ToLower(CultureInfo cultureInfo)
Cele 3 metode fac acelasi lucru, cel mai mult m-a interesat daca exista diferente de performanta intre ele. Am rulat codul de mai jos de 100.000.000 de ori.
string uppertText = "Salut. Ce MAI fACI?";
CultureInfo cultureInfo = CultureInfo.CurrentCulture;
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
for( int i=0; i<100000000; i++)
{
string lowerText = upperText.ToLower();
//string lowerText = upperText.ToLowerInvariant();
//string lowerText = upperText.ToLower(cultureInfo);
}
stopwatch.Stop();
Console.WriteLine("Elapsed type: {0}",stopwatch.Elapsed);

Rezultatul pe care l-am obtinut este destul de interesant:
  • ToLower() - 10.51 s
  • ToLowerInvariant() - 17.32 s
  • ToLower(CultureInfo cultureInfo) - 8.52 s
Daca vreti o performanta si mai mare, puteti sa va implementati propia metoda care parcurge sirul de caractere si pentru fiecare caracter care este litera mare sa il faca lower case. Pentru aceasta implementare am obtinut un timp de 1.89 s.
 public static string ToLowerTest(this string value)
{
char[] output = value.ToCharArray();
for (int i = 0; i < output.Length; i++)
{
if (output[i] >= 'A' &&
output[i] <= 'Z')
{
output[i] = (char)(output[i] + 32);
}
}
return new string(output);
}

Comments

  1. Dacă lucrezi doar cu caractere ASCII e ok, ToLowerTest va face ce trebuie, dar nu mi se pare un mare spor de viteză. În momentul în care apelezi metoda ToLowerTest, timpul cel mai mare va fi ocupat de cele două alocări de memorie - copierea în 'output' și apoi alocarea pentru stringul returnat - la care se adaugă copierea în noul string (dacă nu cumva copierea de pe urmă este realizată cu move semantics).
    Dacă vrei un spor mai mare de performanță, you go native (lași un milion de stringuri la îndemîna unei funcții în C(++) care să facă treaba pentru tine). Asta, desigur, dacă vrei spor real de performanță :)

    ReplyDelete
  2. Iar sa utilizezi un dll de C++ in .NET implica(in afara codului) si niste costuri de transmisie ....

    ReplyDelete
  3. Diferenta intre ToLower() simplu si ToLower(CultureInfo) e mica si usor de explicat, deoarece ToLower() obtine de fiecare date CurrentCulture si CurrentThread, pe cand ToLower(CultureInfo) va primi referinta la CultureInfo "gata obtinuta" de fiecare data.

    ToLowerInvariant nu face chiar acelasi lucru, ci va folosi InvariantCulture, evident (chiar daca culture curenta e en-US, nu e garanta ca va face exact acelasi lucru).

    In spate, toate apeleaza TextInfo.InternalChangeCaseString care nu m-as mira sa apeleze cod nativ gen tolower din wctype.h... (nu are rost sa reinventeze roata)

    Cand e vorba de comparare de stringuri, se recomanda oricum ToUpperInvariant in loc de ToLowerInvariant. (ToUpper e un pic mai optimizat si mai "safe" in unele cazuri obscure).

    ReplyDelete

Post a Comment

Popular posts from this blog

Windows Docker Containers can make WIN32 API calls, use COM and ASP.NET WebForms

After the last post , I received two interesting questions related to Docker and Windows. People were interested if we do Win32 API calls from a Docker container and if there is support for COM. WIN32 Support To test calls to WIN32 API, let’s try to populate SYSTEM_INFO class. [StructLayout(LayoutKind.Sequential)] public struct SYSTEM_INFO { public uint dwOemId; public uint dwPageSize; public uint lpMinimumApplicationAddress; public uint lpMaximumApplicationAddress; public uint dwActiveProcessorMask; public uint dwNumberOfProcessors; public uint dwProcessorType; public uint dwAllocationGranularity; public uint dwProcessorLevel; public uint dwProcessorRevision; } ... [DllImport("kernel32")] static extern void GetSystemInfo(ref SYSTEM_INFO pSI); ... SYSTEM_INFO pSI = new SYSTEM_INFO(...

How to audit an Azure Cosmos DB

In this post, we will talk about how we can audit an Azure Cosmos DB database. Before jumping into the problem let us define the business requirement: As an Administrator I want to be able to audit all changes that were done to specific collection inside my Azure Cosmos DB. The requirement is simple, but can be a little tricky to implement fully. First of all when you are using Azure Cosmos DB or any other storage solution there are 99% odds that you’ll have more than one system that writes data to it. This means that you have or not have control on the systems that are doing any create/update/delete operations. Solution 1: Diagnostic Logs Cosmos DB allows us activate diagnostics logs and stream the output a storage account for achieving to other systems like Event Hub or Log Analytics. This would allow us to have information related to who, when, what, response code and how the access operation to our Cosmos DB was done. Beside this there is a field that specifies what was th...

Cloud Myths: Cloud is Cheaper (Pill 1 of 5 / Cloud Pills)

Cloud Myths: Cloud is Cheaper (Pill 1 of 5 / Cloud Pills) The idea that moving to the cloud reduces the costs is a common misconception. The cloud infrastructure provides flexibility, scalability, and better CAPEX, but it does not guarantee lower costs without proper optimisation and management of the cloud services and infrastructure. Idle and unused resources, overprovisioning, oversize databases, and unnecessary data transfer can increase running costs. The regional pricing mode, multi-cloud complexity, and cost variety add extra complexity to the cost function. Cloud adoption without a cost governance strategy can result in unexpected expenses. Improper usage, combined with a pay-as-you-go model, can result in a nightmare for business stakeholders who cannot track and manage the monthly costs. Cloud-native services such as AI services, managed databases, and analytics platforms are powerful, provide out-of-the-shelve capabilities, and increase business agility and innovation. H...