Skip to content

Commit

Permalink
Speedup creating sha1 digest string
Browse files Browse the repository at this point in the history
Instead of using sprintf to convert the byte array into the hex string,
just implement the conversion manually.

`my $a; my int $i := 0; my int $s := nqp::time; while $i++ < 1_000_000 { $a := nqp::sha1("a") }; say(nqp::div_n(nqp::time - $s, 1000000000)); say($a)`
goes from ~1.44s to ~0.48s. However, real-life impact will be much less,
since we usually hash much larger strings and then the main cost is the
UTF8 encoding and actual hashing.
  • Loading branch information
MasterDuke17 committed Dec 19, 2022
1 parent 42a3a2c commit 8f90dc7
Showing 1 changed file with 7 additions and 6 deletions.
13 changes: 7 additions & 6 deletions 3rdparty/sha1/sha1.c
Expand Up @@ -225,15 +225,16 @@ void SHA1_Digest(SHA1Context* context, unsigned char digest[SHA1_DIGEST_SIZE])
void SHA1Final(SHA1Context *context, char *output)
{
unsigned char digest[20];
int i,j;
int i;
char *c = output;

SHA1_Digest(context, digest);

for (i = 0; i < SHA1_DIGEST_SIZE/4; i++) {
for (j = 0; j < 4; j++) {
sprintf(c,"%02X", digest[i*4+j]);
c += 2;
}
unsigned char *d = digest;
const char *hex = "0123456789ABCDEF";
for (i = 0; i < 20; i++) {
*c++ = hex[(*d >> 4) & 0xF];
*c++ = hex[(*d++) & 0xF];
}
*c = 0;
}

0 comments on commit 8f90dc7

Please sign in to comment.