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(

ADO.NET provider with invariant name 'System.Data.SqlClient' could not be loaded

Today blog post will be started with the following error when running DB tests on the CI machine: threw exception: System.InvalidOperationException: The Entity Framework provider type 'System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer' registered in the application config file for the ADO.NET provider with invariant name 'System.Data.SqlClient' could not be loaded. Make sure that the assembly-qualified name is used and that the assembly is available to the running application. See http://go.microsoft.com/fwlink/?LinkId=260882 for more information. at System.Data.Entity.Infrastructure.DependencyResolution.ProviderServicesFactory.GetInstance(String providerTypeName, String providerInvariantName) This error happened only on the Continuous Integration machine. On the devs machines, everything has fine. The classic problem – on my machine it’s working. The CI has the following configuration: TeamCity .NET 4.51 EF 6.0.2 VS2013 It see

Navigating Cloud Strategy after Azure Central US Region Outage

 Looking back, July 19, 2024, was challenging for customers using Microsoft Azure or Windows machines. Two major outages affected customers using CrowdStrike Falcon or Microsoft Azure computation resources in the Central US. These two outages affected many people and put many businesses on pause for a few hours or even days. The overlap of these two issues was a nightmare for travellers. In addition to blue screens in the airport terminals, they could not get additional information from the airport website, airline personnel, or the support line because they were affected by the outage in the Central US region or the CrowdStrike outage.   But what happened in reality? A faulty CrowdStrike update affected Windows computers globally, from airports and healthcare to small businesses, affecting over 8.5m computers. Even if the Falson Sensor software defect was identified and a fix deployed shortly after, the recovery took longer. In parallel with CrowdStrike, Microsoft provided a too