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. O mare problema de performanta in operatiuni .NET cu stringuri este ca suporta toate caracterele Unicode. Principalul motiv pentru care se foloseste ToLower, cel putin din experienta mea, este comparare de stringuri. Dar deja exista niste metode specifice de comparare de stringuri care folosesc enumul StringComparison. StringComparison are si niste valori ca Ordinal si OrdinalIgnoreCase care sint folosite atunci cind nu mai conteaza Unicodeul, ci se presupune ca fiecare caracter are un byte. De obicei, viteza cu Ordinal e de 3-4 ori mai mare decit operatiunile normale.

    Iar la faza cu C++ ca sa mearga repede este bullshit. Nu toate operatiunile .NET sint managed code, mai ales cele de baza, iar daca vrei sa fii mai catolic decit papa poti oricind sa iti faci propriile metode unsafe si sa lucrezi cu pointeri. Daca nu ma crezi, baga niste reflection pe metodele .Net. (da, stiu, reflectionul nu exista in C++, dar nu e greu de invatat >:))

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

    ReplyDelete
  4. 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

How to check in AngularJS if a service was register or not

There are cases when you need to check in a service or a controller was register in AngularJS.
For example a valid use case is when you have the same implementation running on multiple application. In this case, you may want to intercept the HTTP provider and add a custom step there. This step don’t needs to run on all the application, only in the one where the service exist and register.
A solution for this case would be to have a flag in the configuration that specify this. In the core you would have an IF that would check the value of this flag.
Another solution is to check if a specific service was register in AngularJS or not. If the service was register that you would execute your own logic.
To check if a service was register or not in AngularJS container you need to call the ‘has’ method of ‘inhector’. It will return TRUE if the service was register.
if ($injector.has('httpInterceptorService')) { $httpProvider.interceptors.push('httpInterceptorService&#…

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.51EF 6.0.2VS2013
It seems that there …

Run native .NET application in Docker (.NET Framework 4.6.2)

Scope
The main scope of this post is to see how we can run a legacy application written in .NET Framework in Docker.

Context
First of all, let’s define what is a legacy application in our context. By a legacy application we understand an application that runs .NET Framework 3.5 or higher in a production environment where we don’t have any more the people or documentation that would help us to understand what is happening behind the scene.
In this scenarios, you might want to migrate the current solution from a standard environment to Docker. There are many advantages for such a migration, like:

Continuous DeploymentTestingIsolationSecurity at container levelVersioning ControlEnvironment Standardization
Until now, we didn’t had the possibility to run a .NET application in Docker. With .NET Core, there was support for .NET Core in Docker, but migration from a full .NET framework to .NET Core can be costly and even impossible. Not only because of lack of features, but also because once you…