5

Micro-optimisation; ‘starts with single-character string’ vs str[0]

 3 years ago
source link: https://stevedrivendevelopment.com/2015/10/22/micro-optimisation-starts-with-single-character-string-vs-str0/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Micro-optimisation; ‘starts with single-character string’ vs str[0]

I’m writing code with very stringent performance characteristics, and it’s a string validation routine. One part is a short-cut that kicks in if we might potentially be looking at a JSON object or JSON array. I’d written

var mightBeJson = value.StartsWith("{") || value.StartsWith("[")) {

as a short-cut. Turned out that since this is almost the first thing that happened in the code, this made a massive, terrible hit on performance. Switching to treating the string as a char array makes a massive difference;

 var mightBeJson = value[0] == '[' || value[0] == '{';

Night and day difference!

Takeaway — never compare single-character strings like “X” when you can compare chars like ‘X’ directly.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK