Skip to content

Instantly share code, notes, and snippets.

@strangezakary
Created December 19, 2020 19:47
Show Gist options
  • Save strangezakary/beb452ca76015d755f6a46109616e46b to your computer and use it in GitHub Desktop.
Save strangezakary/beb452ca76015d755f6a46109616e46b to your computer and use it in GitHub Desktop.
Really Fast String Length
// This Requires SSE 4.2, Steam hardware survey says this is supported on 97.81% of PCs
// This is REALLY fast, even with -O2 it usually beats the the CRT Implementation
//
// In most of my tests this is around 50x faster with small strings with -Od (with -O2 its closer to 10-15x faster)
//
static size_t
FastStringLength(char* String)
{
size_t Result = 0;
__m128i* Memory = (__m128i *)String;
const __m128i Zeros = _mm_setzero_si128();
for (; Memory++; Result += 16)
{
const __m128i Data = _mm_loadu_si128(Memory);
if (_mm_cmpistrc(Data, Zeros, _SIDD_CMP_EQUAL_EACH | _SIDD_UBYTE_OPS | _SIDD_LEAST_SIGNIFICANT))
{
const int Index = _mm_cmpistri(Data, Zeros, _SIDD_CMP_EQUAL_EACH | _SIDD_UBYTE_OPS | _SIDD_LEAST_SIGNIFICANT);
return Result + Index;
}
}
return(Result);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment