Performance issue: comparing to String.Format

后端 未结 6 637
攒了一身酷
攒了一身酷 2020-12-08 22:32

A while back a post by Jon Skeet planted the idea in my head of building a CompiledFormatter class, for using in a loop instead of String.Format().

6条回答
  •  心在旅途
    2020-12-08 22:56

    Don't stop now!

    Your custom formatter might only be slightly more efficient than the built-in API, but you can add more features to your own implementation that would make it more useful.

    I did a similar thing in Java, and here are some of the features I added (besides just pre-compiled format strings):

    1) The format() method accepts either a varargs array or a Map (in .NET, it'd be a dictionary). So my format strings can look like this:

    StringFormatter f = StringFormatter.parse(
       "the quick brown {animal} jumped over the {attitude} dog"
    );
    

    Then, if I already have my objects in a map (which is pretty common), I can call the format method like this:

    String s = f.format(myMap);
    

    2) I have a special syntax for performing regular expression replacements on strings during the formatting process:

    // After calling obj.toString(), all space characters in the formatted
    // object string are converted to underscores.
    StringFormatter f = StringFormatter.parse(
       "blah blah blah {0:/\\s+/_/} blah blah blah"
    );
    

    3) I have a special syntax that allows the formatted to check the argument for null-ness, applying a different formatter depending on whether the object is null or non-null.

    StringFormatter f = StringFormatter.parse(
       "blah blah blah {0:?'NULL'|'NOT NULL'} blah blah blah"
    );
    

    There are a zillion other things you can do. One of the tasks on my todo list is to add a new syntax where you can automatically format Lists, Sets, and other Collections by specifying a formatter to apply to each element as well as a string to insert between all elements. Something like this...

    // Wraps each elements in single-quote charts, separating
    // adjacent elements with a comma.
    StringFormatter f = StringFormatter.parse(
       "blah blah blah {0:@['$'][,]} blah blah blah"
    );
    

    But the syntax is a little awkward and I'm not in love with it yet.

    Anyhow, the point is that your existing class might not be much more efficient than the framework API, but if you extend it to satisfy all of your personal string-formatting needs, you might end up with a very convenient library in the end. Personally, I use my own version of this library for dynamically constructing all SQL strings, error messages, and localization strings. It's enormously useful.

提交回复
热议问题