bolerio / mjson

Lean JSON Library for Java, with a compact, elegant API.
Apache License 2.0
82 stars 26 forks source link

escaper caching #9

Open rob42 opened 9 years ago

rob42 commented 9 years ago

Hi, Found I can get a huge increase in speed by caching in the escaper. In my case I am outputting periodic updates to the same data, so its especially useful. the escape method was using 5% CPU, now its below 1%. I know you dont want any dependencies but I used Google guava cache. Code is here if you want to use it:

escapeHash = CacheBuilder.newBuilder()
                   .maximumSize(1000)
                   .build(
                           new CacheLoader<CharSequence, String>() {
                             public String load(CharSequence plainText) throws Exception {
                                 StringBuilder escapedString = new StringBuilder(plainText.length() + 20);
                                try {
                                  escapeJsonString(plainText, escapedString);
                                } catch (IOException e) {
                                  throw new RuntimeException(e);
                                }
                                return escapedString.toString();
                             }
                           });
      }

      public String escapeJsonString(CharSequence plainText) {
        return escapeHash.getUnchecked(plainText);
      }
bolerio commented 9 years ago

That's interesting and I'd do something about it. You are right, I wouldn't want any dependencies on the project :)

rob42 commented 9 years ago

BTW I treid a raw ConcurrentHashMap, but it kept growing and slowing, so that doesnt work without an evictor.