Skip to content

playing with small string optimisation #5317

@uzi18

Description

@uzi18

@TD-er @tonhuisman puzzles here :)

Take a code from lines:

String getCNonce(const int len) {
static const char alphanum[] = "0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
String s;
for (int i = 0; i < len; ++i) {
// FIXME TD-er: Is this "-1" correct? The mod operator makes sure we never reach the sizeof index
s += alphanum[rand() % (sizeof(alphanum) - 1)];
}
return s;
}

pio run -e max_ESP32_16M1M_ETH

RAM:   [==        ]  19.2% (used 62768 bytes from 327680 bytes)
Flash: [======    ]  63.7% (used 2672485 bytes from 4194304 bytes)

Get rid of string and generate it in loop:

String getCNonce(const int len) {
  char alphanum[26+26+10+1];

  for (int i = 0; i < 26; ++i) {
    if (i<10) alphanum[i] = '0'+i;
    alphanum[i+10]= 'A'+i;
    alphanum[i+10+26]= 'a'+i;
  }

  String s;

  for (int i = 0; i < len; ++i) {
    s += alphanum[rand() % (sizeof(alphanum) - 1)];
  }

RAM:   [==        ]  19.2% (used 62768 bytes from 327680 bytes)
Flash: [======    ]  63.7% (used 2672469 bytes from 4194304 bytes)

So got -16 bytes of flash.

Now get rid with alphanum:

String getCNonce(const int len) {
  String s;

  const int numbers = '9'-'0'+ 1;
  const int alphas = 'Z'-'A'+ 1;
  const int allchars = 2*alphas+numbers; 
  char a;

  for (int i = 0; i < len; ++i) {
   int j = rand() % (allchars - 1);
   if (j<numbers) a = ('0'+j);
   else if (j<numbers+alphas) a = ('A'+j);
   else a = ('a'+j);
   s += a;
  }

  return s;
}

RAM:   [==        ]  19.2% (used 62768 bytes from 327680 bytes)
Flash: [======    ]  63.7% (used 2672453 bytes from 4194304 bytes)

So -32 bytes
add alphanum one more time (just for sizeof):

String getCNonce3(const int len) {
  static const char alphanum[] =   "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  String s;

  const int numbers = '9'-'0'+ 1;
  const int alphas = 'Z'-'A'+ 1;
  const int allchars = 2*alphas+numbers; 
  char a;

  for (int i = 0; i < len; ++i) {
   int j = rand() % (sizeof(alphanum) - 1);
   if (j<numbers) a = ('0'+j);
   else if (j<numbers+alphas) a = ('A'+j);
   else a = ('a'+j);
   s += a;
  }

  return s;
}

RAM:   [==        ]  19.2% (used 62768 bytes from 327680 bytes)
Flash: [======    ]  63.7% (used 2672429 bytes from 4194304 bytes)

So -56 bytes it is like a magic
how it is possible?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions