<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Dmytro Dumanskiy on Medium]]></title>
        <description><![CDATA[Stories by Dmytro Dumanskiy on Medium]]></description>
        <link>https://medium.com/@ddumanskiy?source=rss-acd4d4d667cc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*J97qdNLIDwd_4V1K.</url>
            <title>Stories by Dmytro Dumanskiy on Medium</title>
            <link>https://medium.com/@ddumanskiy?source=rss-acd4d4d667cc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 10:53:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ddumanskiy/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Micro optimizations in Java. String.replaceAll]]></title>
            <link>https://medium.com/javarevisited/micro-optimizations-in-java-string-replaceall-c6d0edf2ef6?source=rss-acd4d4d667cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6d0edf2ef6</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[string]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Dmytro Dumanskiy]]></dc:creator>
            <pubDate>Thu, 03 Sep 2020 08:32:59 GMT</pubDate>
            <atom:updated>2020-09-08T09:13:17.229Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4aFXOkCP07c5A-yyqZye4Q.png" /><figcaption>String.replaceAll</figcaption></figure><p>In this post, we will discuss the usage of another prevalent code constructions, the <em>String.replaceAll</em> and <em>String.replace </em>methods, and we will investigate how it affects the performance of your code in Java 11 and what you can do about it.</p><p><strong>(Please consider all the code below from the point of performance)</strong></p><p><strong>(Please don’t focus on numbers, they are just metrics to prove the point)</strong></p><h3>String.replaceAll</h3><p>I wouldn’t say I like to make up the examples, so this time, we’ll start right away from the existing codebase of the Spring Framework. Let’s look <a href="https://github.com/spring-projects/spring-framework/blob/master/spring-messaging/src/main/java/org/springframework/messaging/rsocket/MetadataEncoder.java#L110">at this line of the MetadataEncoder class</a> of the spring-messaging module:</p><pre>value = value.contains(&quot;.&quot;) ? value.replaceAll(&quot;\\.&quot;,&quot;%2E&quot;) : value;</pre><p>Do you see what is wrong here?</p><p>All this code is trying to do is encode the <em>dot</em> symbol and pass the result later to the HTTP URL. I was very lucky to find that particular code snippet in the popular codebase. It has a few things in a single line.</p><p>If you’re an experienced developer, you already know that the <a href="http://javarevisited.blogspot.sg/2017/01/string-replaceall-example-how-to-replace-all-characters-and-substring.html#axzz4upeaPBNd"><em>String.replaceAll</em> </a>method is using the regular expression pattern as the first parameter:</p><pre>public String replaceAll(String regex, String replacement) {<br>    return Pattern.<em>compile</em>(regex).matcher(this)<br>                  .replaceAll(replacement);<br>}</pre><p>However, in the above code, we replace only <em>dot</em> character. Very often, when you perform the replacement operation, you don’t need any pattern matching. You can just use another very similar and lighter method in terms of the performance — the <em>String.replace:</em></p><pre>public String replace(CharSequence target, CharSequence replacement)</pre><p>For example, when you need to replace a single word or a single character like in our example.</p><p><strong>Note: In Java 8 the <em>String.replace </em>method<em> </em>was using the <em>Pattern</em> inside as the <em>String.replaceAll</em>. However, since Java 9, it has changed. And that gives us a large room for optimizations in the existing codebase.</strong></p><p>Also, the usage of the methods <em>String.replace</em> and <em>String.replaceAll</em> seems like error-prone by design. That’s because when you start typing something in the IDE and you see both these methods closely, you might think that the <em>String.replace</em> replaces only the first occurrence while the <em>replaceAll</em> replaces all. And intuitively you will choose the <em>String.replaceAll</em> over the <em>String.replace</em>.</p><p>Another interesting thing here is that the code above already has a micro-optimization, it’s the <em>value.contains(“.”)</em> method usage. So the string is checked for the <em>dot</em> symbol to avoid pattern matching if there is nothing to replace.</p><p>Okay, let’s fix the example above:</p><pre>value = value.replace(&quot;.&quot;, &quot;%2E&quot;);</pre><p>we can also try to apply the <em>String.indexOf(“.”)</em> optimization and check if that helps in the case of the <em>String.replace</em> method usage in Java 11:</p><pre>value = value.contains(&quot;.&quot;) ? value.replace(&quot;.&quot;, &quot;%2E&quot;) : value;</pre><p>Let’s write the benchmark:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/779707eef854b5fccb957eee6f32085d/href">https://medium.com/media/779707eef854b5fccb957eee6f32085d/href</a></iframe><p>Results (lower score means faster) :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/18a3d88972d45bc45a02482a862b16d6/href">https://medium.com/media/18a3d88972d45bc45a02482a862b16d6/href</a></iframe><p>It looks like usage of the <em>String.indexOf(“.”)</em> with the <em>String.replaceAll</em> method, in fact, makes sense, even for the empty input string, compiling and matching the pattern takes too much time. ~50x difference is huge. The same applies to the input string without any dot symbols. And when the actual replacement work had to be performed, the <em>String.replace</em> method outperforms the <em>String.replaceAll</em> <strong>by three times</strong>.</p><p>Also, it seems like the <em>String.indexOf</em> optimization doesn’t make any sense with the <em>String.replace</em> method in Java 11 anymore, while it was required in Java 8 when we had a pattern matching inside. Now it even makes it a bit slower. That’s because of the <em>String.replace</em> method implementation, as it already performs <em>String.indexOf</em> search inside. So we’re doing the double job here.</p><p>“But you can precompile the regular pattern expression and use it in order to improve the performance of <em>String.replaceAll</em> method”, you would say. Agree. In fact, we do that a lot in <a href="https://blynk.io/">Blynk</a>.</p><p>Let’s check how precompiled pattern changes the numbers:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0dab4864acae06bcfb6a9abaf69ce814/href">https://medium.com/media/0dab4864acae06bcfb6a9abaf69ce814/href</a></iframe><p>Results (lower score means faster) :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/99e5ff11bf905abdd2fb0089835f31ff/href">https://medium.com/media/99e5ff11bf905abdd2fb0089835f31ff/href</a></iframe><p>Yes, the numbers are better now. However, still not that good as in the case of the <em>String.replace</em> method. We can try to focus on optimizing the regular pattern even more, but there are already enough posts about it.</p><p>You might think that an initial example is just a single place, and it’s pretty rare. Let’s look into the GitHub:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*06jYy0ZYjpVV2_WSlL0HDQ.png" /></figure><p>GitHub just indexed some repositories, and on the first screen, five out of the six <em>String.replaceAll</em> usages could be replaced with <em>String.replace</em>! Yes, many projects are still on Java 8, which won’t make any difference for them. However, after most developers migrate to Java 11, we’ll have a lot of the slow legacy code out there. We can start improving it right away.</p><h3>StringUtils.replace</h3><p>Before Java 11, when you had a hot path with the <em>String.replace </em>method, you had to find the faster alternatives in some 3-d party libraries or even write your own custom version. The most known 3-d party alternative is the Apache Commons <em>StringUtils.replace</em> method.</p><p>An example of a custom <em>replace</em> method could be found, for instance, in the Spring Framework. <a href="https://medium.com/r?url=https%3A%2F%2Fgithub.com%2Fspring-projects%2Fspring-framework%2Fblob%2Fmaster%2Fspring-core%2Fsrc%2Fmain%2Fjava%2Forg%2Fspringframework%2Futil%2FStringUtils.java%23L415">Here it is</a>.</p><p>Let’s look at another Spring <a href="https://github.com/spring-projects/spring-framework/blob/874574513c47287d86fb8a3e943a81910b587395/spring-context/src/main/java/org/springframework/instrument/classloading/ShadowingClassLoader.java#L148">code snippet</a>:</p><pre>String internalName = StringUtils.<em>replace</em>(className, &quot;.&quot;, &quot;/&quot;);</pre><p>Do you see what is wrong here?</p><p>Let’s check Spring (latest source code), Apache Commons (latest version 3.11 of commons-lang3), and Java methods in our benchmark:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ff1dab1b519dddc9fbbc80edcef9fc8/href">https://medium.com/media/9ff1dab1b519dddc9fbbc80edcef9fc8/href</a></iframe><p>Results (lower score means faster) :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/580e0d67c8da7b95644decf2f818c993/href">https://medium.com/media/580e0d67c8da7b95644decf2f818c993/href</a></iframe><p>Hm, it looks like all methods are pretty close. Apache Commons is a bit slower, but that’s because it has additional logic for handling the case insensitive replacement. So everything makes sense.</p><p>And now, as we have similar performance, we don’t need a custom method or 3-d party library anymore in order to perform the fast <em>String.replace</em> in Java 11.</p><p>But something still not ok with this line:</p><pre>return value.replace(&quot;.&quot;, &quot;/&quot;);</pre><p>Do you see what is wrong here?</p><p>Contrary to the first example where actual string replacement happens, here we have a single character both for the search and replace. And as we know, Java has a specialized version for character replacement:</p><pre>String replace(char oldChar, char newChar)</pre><p>Let’s add it to our benchmark as well:</p><pre>@Benchmark<br>public String replaceChar() {<br>    return value.replace(&#39;.&#39;, &#39;/&#39;);<br>}</pre><p>Apache Commons library also has <em>StringUtils.replaceChars</em>, but it uses <em>String.replace(char, char)</em> inside, so we’ll skip it. And we are one more step closer to eliminate this 3-d party library from your project.</p><p>Results (lower score means faster) :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e7c66fe651a246a5b7479ac977c3a7dc/href">https://medium.com/media/e7c66fe651a246a5b7479ac977c3a7dc/href</a></iframe><p>Java character specialized version for the single char replacement <strong>four times</strong> faster than overloaded <em>String.replace(String, String) </em>and the custom Spring<em> </em>approach. The funny thing is that even in Java 8 <em>String.replace(char, char)</em> is optimized well enough. So Spring could safely use the <em>String.replace(char, char)</em>.</p><h3>String.remove</h3><p>I hope you aren’t tired yet :)? Let’s look at this last code example:</p><pre>value = value.replace(&quot;.&quot;, &quot;&quot;);</pre><p>Do you see what is wrong here?</p><p>Unfortunately, Java still doesn’t have the <em>String.remove</em> method. As an alternative, we could use <em>String.replace(char, char)</em> method, but Java doesn’t have empty character literal as well, we can’t write code like that:</p><pre>value.replace(&#39;.&#39;, &#39;&#39;);</pre><p>So, instead, we have to use a “hack” above.</p><p>Fortunately, there are many 3-d party implementations out there like Apache Commons <em>StringUtils.remove(String, char)</em>. Spring, for example, uses own custom implementation for that based on own custom <em>replace</em> method:</p><pre>public static String delete(String inString, String pattern) {<br>   return StringUtils.<em>replace</em>(inString, pattern, &quot;&quot;);<br>}</pre><p>Let’s check Spring, Apache Commons, and Java methods in our benchmark again for the <em>remove</em> operation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/77eb0fee7e19a977ea398065d9a85c8a/href">https://medium.com/media/77eb0fee7e19a977ea398065d9a85c8a/href</a></iframe><p>Results (lower score means faster) :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f7d7c038810d0655c82d09cf56ab93c/href">https://medium.com/media/3f7d7c038810d0655c82d09cf56ab93c/href</a></iframe><p>Specialized Apache Commons version wins <strong>by almost three times</strong>. The interesting thing here is that even specialized and optimized char removal is slower than char replacement in the <em>String.replace(char, char)</em>. There is definitely still room for even further improvement.</p><p>Hopefully, someday we’ll see that in Java.</p><h3>Conclusions</h3><ul><li>Use Java 11</li><li>Use the S<em>tring.replace</em> over the <em>String.replaceAll</em> when possible</li><li>If you have to use the <em>String.replaceAll</em>, try to precompile the regular expression in the hot paths</li><li>Go with a specialized version of the <em>String.replace(char, char)</em> instead of the <em>String.replace(String, String)</em> when you can</li><li>For hot paths, you’ll still need to consider 3-d party libraries or custom methods instead of the <em>String.replace(value, “”)</em> code pattern</li></ul><p>Here is a <a href="https://github.com/doom369/java-micro-optimizations">source code</a> of benchmarks so that you can try it yourself.</p><p>Thank you for your attention, and stay tuned.</p><p>Previous post: <a href="https://medium.com/javarevisited/micro-optimizations-in-java-good-nice-and-slow-enum-261e6f77bd2e?source=friends_link&amp;sk=2efd362f40b01c300b09f425d57a9bb0">Micro optimizations in Java. Good, nice and slow Enum</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6d0edf2ef6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/micro-optimizations-in-java-string-replaceall-c6d0edf2ef6">Micro optimizations in Java. String.replaceAll</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Micro optimizations in Java. Good, nice and slow Enum]]></title>
            <link>https://medium.com/javarevisited/micro-optimizations-in-java-good-nice-and-slow-enum-261e6f77bd2e?source=rss-acd4d4d667cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/261e6f77bd2e</guid>
            <category><![CDATA[enumeration]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Dmytro Dumanskiy]]></dc:creator>
            <pubDate>Thu, 20 Aug 2020 12:24:12 GMT</pubDate>
            <atom:updated>2020-09-07T07:59:37.488Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KwgsfwwCDeNrCC2HME2dDQ.png" /></figure><p>Enums are crucial part of every application larger than “Hello World“. We use them everywhere. They are actually very useful: they restrict the input, allow you to compare the values by the reference, provide compile-time checks, and make the code easier to read. However, using Enums has a few performance downsides. And we’ll review them in this post.</p><p><strong>(Please consider all the code below from the point of performance)</strong></p><p><strong>(Please do not focus on numbers, they are just examples to prove the point)</strong></p><h3>Enum.valueOf</h3><p>In <a href="https://blynk.io/">Blynk</a>, one of the most popular features is called “Widget Property”. It’s when you can change the appearance of the visual widget in real-time by sending from the hardware the command like that:</p><pre>Blynk.setProperty(v1, “LABEL”, “My New Label”);</pre><p>Let’s take a look at existing Enum from our server:</p><pre>enum WidgetProperty {<br> LABEL,<br> COLOR,<br> ON_LABEL,<br> OFF_LABEL,<br> MIN,<br> MAX <br>}</pre><p>And now look at this basic code:</p><pre>String inWidgetProperty;<br>...<br>WidgetProperty property = WidgetProperty.valueOf(inWidgetProperty)</pre><p>Do you see what is wrong here?</p><p>Let’s rewrite the above code and create our own method based on the <em>switch </em>statement:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/63cdff9f33a7290cd30e3f413cfd2585/href">https://medium.com/media/63cdff9f33a7290cd30e3f413cfd2585/href</a></iframe><p>This method isn’t precisely the same, as it doesn’t throw the <em>IllegalArgumentException</em> in case of an unknown value. However, it’s done on purpose. Because, as you know, throwing and creating the exception (because of the stack trace) is an expensive operation.</p><p>Let’s make a benchmark:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f78a3bfa34e7332bd5adce1923135a9/href">https://medium.com/media/2f78a3bfa34e7332bd5adce1923135a9/href</a></iframe><p>Results (lower score means faster):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1bfca956dda4cabe72b061b027c0fede/href">https://medium.com/media/1bfca956dda4cabe72b061b027c0fede/href</a></iframe><p>Hm… Our custom method with the <em>switch</em> statement is two times faster than <em>Enum.valueOf. </em>Something is wrong here. We need to go deeper.</p><p>As you probably know, <em>enum</em> classes don’t have the Java <em>valueOf()</em> method. The compiler generates it during the compilation. So we need to look into the byte code of the generated class to understand what is going on there:</p><pre> LDC Lstring/WidgetProperty;.class<br> ALOAD 0<br> INVOKESTATIC java/lang/Enum.valueOf (Ljava/lang/Class;Ljava/lang/String;)Ljava/lang/Enum;<br> CHECKCAST string/WidgetProperty<br> ARETURN</pre><p>Looks like <em>java.lang.Enum.valueOf</em> method is invoked inside <em>WidgetPtoperty.valueOf</em> method. Fortunately, this method is present in the Java code. Let’s check it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a43668bfd8542ed10e10f7b16d446bce/href">https://medium.com/media/a43668bfd8542ed10e10f7b16d446bce/href</a></iframe><p>And <em>enumConstantDirectory</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dacae3b829c10374c5d89968cea915aa/href">https://medium.com/media/dacae3b829c10374c5d89968cea915aa/href</a></iframe><p>Aha, so all we have here is a regular volatile <em>HashMap</em> with the enum names as the keys. And it looks like in that particular case the <em>switch</em> statement just outperforms the <em>HashMap.get() </em>method.</p><p>Let’s add <em>valueOf</em> with own <em>HashMap</em> implementation to the test as well:</p><pre>private final static Map&lt;String, WidgetProperty&gt; <em>cache</em>;<br>static {<br>    <em>cache </em>= new HashMap&lt;&gt;();<br>    for (WidgetProperty widgetProperty : <em>values</em>()) {<br>        <em>cache</em>.put(widgetProperty.name(), widgetProperty);<br>    }<br>}</pre><pre>public static WidgetProperty enumMap(String value) {<br>    return <em>cache</em>.get(value);<br>}</pre><p>Results (lower score means faster, <em>enumMap</em> results attached to the prev test):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/27997f40f73144cba054eeb7b4932056/href">https://medium.com/media/27997f40f73144cba054eeb7b4932056/href</a></iframe><p>Own <em>HashMap</em> implementation seems faster than regular <em>Enum.valueOf()</em> but still slower than the <em>switch</em> statement.</p><p>Let’s rewrite the test to have the random input:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad5099f5f34e9720a03c9ed7d92de53e/href">https://medium.com/media/ad5099f5f34e9720a03c9ed7d92de53e/href</a></iframe><p>Results (lower score means faster):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f97636c1ad5bbeffcf17bdda556a14a0/href">https://medium.com/media/f97636c1ad5bbeffcf17bdda556a14a0/href</a></iframe><p>Interesting… Now, with the random input, the switch statement is 2 times slower. Looks like the difference is due to the branch prediction according to the Andrei Pangin comment. And the fastest option would be our own <em>Map</em> cache implementation (as it does fewer checks comparing to the <em>Enum.valueOf</em>).</p><h3>Enum.values()</h3><p>Now, let’s consider another example. It’s not so popular as the above one, but still present in many projects:</p><pre>for (WidgetProperty property : WidgetProperty.<em>values</em>()) {<br>   ...<br>}</pre><p>Do you see what is wrong here?</p><p>Again, <em>Enum.values()</em> method is generated during the compilation, so to understand what is wrong there we have to look at the byte code one more time:</p><pre> GETSTATIC string/WidgetProperty.$VALUES : [Lstring/WidgetProperty;<br> INVOKEVIRTUAL [Lstring/WidgetProperty;.clone ()Ljava/lang/Object;<br> CHECKCAST [Lstring/WidgetProperty;<br> ARETURN</pre><p>You don’t need to be a byte code expert to see the <em>.clone()</em> method invocation. So, every time you call the <em>Enum.values()</em> method — the array with the enum values is always copied.</p><p>The solution is pretty obvious — we can cache the<em> Enum.values()</em> method result like that:</p><pre>public static final WidgetProperty[] <em>values </em>= <em>values</em>();</pre><p>And use the cache field instead. Let’s check it with the benchmark:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/25feaaa94e5808a407e5765a85b976d9/href">https://medium.com/media/25feaaa94e5808a407e5765a85b976d9/href</a></iframe><p>I used the loop in that benchmark because, usually, the <em>Enum.values()</em> is used within the loop.</p><p>Results (lower score means faster):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/046e4f766964038740d7ab748d8e874a/href">https://medium.com/media/046e4f766964038740d7ab748d8e874a/href</a></iframe><p>The performance difference here is ~30%. That’s because the loop iteration takes some CPU as well. However, what is more important: after our fix, no allocation happens. And that’s even more important than gained speed improvement.</p><p>You may wonder, why <em>Enum.values()</em> is implemented in this way? Well, the explanation is quite simple. Without <em>copy()</em> method anyone could change the content of the returned array. And that could lead to many problems. So returning the same reference to the array with values that can be easily replaced isn’t the best idea. Immutable arrays would solve that issue, but Java doesn’t have one.</p><p>Yes, this change decreases the readability a bit and you don’t need to use it with every enum. It’s necessary only for really hot paths.</p><p>Check for example <a href="https://github.com/datastax/java-driver/pull/1293/files">this PR for Apache Cassandra jdbc driver</a>, <a href="https://github.com/microsoft/mssql-jdbc/pull/1065/files">mssql-jdbc driver PR</a> or <a href="https://github.com/threadly/litesockets-http/pull/37/files">this PR for http server</a>.</p><h3>Conclusion</h3><ul><li>For hot paths, consider using your own <em>Map</em> cache of the <em>Enum.valueOf()</em> method. As an additional bonus, you could avoid throwing the <em>Exception</em> during the wrong input. That could be a game-changer for some flows</li><li>For hot paths, go with the cached <em>Enum.values()</em> field. This will allow you to decrease the allocation rate</li></ul><p>Here is a <a href="https://github.com/doom369/java-micro-optimizations">source code</a> of benchmarks, so that you can try it yourself.</p><p>Thank you for your attention, and stay tuned.</p><p>Previous post: <a href="https://medium.com/javarevisited/micro-optimizations-in-java-string-equalsignorecase-ea25dfb03f95?source=friends_link&amp;sk=28001856b9085e3c927de376298323fd">Micro optimizations in Java. String.equalsIgnoreCase()</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=261e6f77bd2e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/micro-optimizations-in-java-good-nice-and-slow-enum-261e6f77bd2e">Micro optimizations in Java. Good, nice and slow Enum</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Micro optimizations in Java. String.equalsIgnoreCase()]]></title>
            <link>https://medium.com/javarevisited/micro-optimizations-in-java-string-equalsignorecase-ea25dfb03f95?source=rss-acd4d4d667cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea25dfb03f95</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[string]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Dmytro Dumanskiy]]></dc:creator>
            <pubDate>Thu, 06 Aug 2020 13:38:46 GMT</pubDate>
            <atom:updated>2020-08-26T07:05:41.515Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nu4eSvdtWUGgijOSt9z_Dg.png" /></figure><p>So, in the <a href="https://medium.com/javarevisited/micro-optimizations-in-java-string-equals-22be19fd8416?source=friends_link&amp;sk=61649c9c9fccfb59c0515fcb9f7447ef">previous post</a>, we considered two approaches to improve the performance of the well-known <em>String.equals()</em> method. Now, we’ll look into two other String class methods that you are using every day.</p><p><strong>(Please consider all the below code from the point of performance)</strong></p><p><strong>(Please do not focus on numbers, these are just examples to prove the point)</strong></p><h3>equalsIgnoreCase</h3><p>As usual, we’ll start with the very simple and basic code. This code is pretty common for web servers that have HTTP API and expect some kind of a parameter:</p><pre>if (&quot;hello world&quot;.equals(param.toLowerCase())) {</pre><pre>}</pre><p>What is wrong here?</p><p>It’s pretty obvious. We do <em>toLowerCase()</em> that allocates a new instance of the String object. Now GC has to gather it and making GC busy is always a bad idea for the performance.</p><p>We can easily replace it with <em>String.equalsIgnoreCase()</em>:</p><pre>if (&quot;hello world&quot;.equalsIgnoreCase(param)) {</pre><pre>}</pre><p>Let’s create a benchmark and check whether it’s actually faster (I’ll add more drama by using one of the parameters in the upper case):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9b8e5afa93bbd300a116b87274e571ba/href">https://medium.com/media/9b8e5afa93bbd300a116b87274e571ba/href</a></iframe><p>Note: I added the <em>equals()</em> method so we can use it as a baseline. Also, I tried Apache Commons Lang 3 <em>StringUtils.equalsIgnoreCase()</em>, however, it was slower than the Java version. So I excluded it for simplicity.</p><p>Results (lower score means faster):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/66b7aaf14b59267d4e0439bd05923a4a/href">https://medium.com/media/66b7aaf14b59267d4e0439bd05923a4a/href</a></iframe><p>So what do we see?</p><p><em>equalsIgnoreCase()</em> is 20–50% faster than the <em>equals(param.toLowerCase())</em> pattern<em>.</em> And 25 times faster when the parameter doesn’t match the constant string. Let’s take a look at the <em>String.equalsIgnoreCase()</em> to understand why the difference is so huge for the non-matching parameters:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a9325dbd92ea9120ee426e1a319a047/href">https://medium.com/media/8a9325dbd92ea9120ee426e1a319a047/href</a></iframe><p>Aha, that’s because <em>equalsIgnoreCase()</em> has a string length check and in that particular test, this length is different. So no char matching actually happening.</p><p>Another observation — the more upper case letters the string has, the slower the results. That’s because both <em>toLowerCase</em> and <em>equalsIgnoreCase</em> iterate over all chars and perform <em>Character.toLowerCase()</em> if chars don’t match.</p><p>And finally, the <em>equals()</em> method outperforms <em>equalsIgnoreCase()</em> by 2.5 times.</p><p>“Okay, but Java 8 a bit outdated these days”, you would say. I agree, so let’s repeat the test with Java 11.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/21746c825cf59d521b5a24179c48afd8/href">https://medium.com/media/21746c825cf59d521b5a24179c48afd8/href</a></iframe><p>Wait a minute… That’s not what we expected. Looks like in Java 11 the performance of both options is similar. And with the specific input data the <em>equals(param.toLowerCase())</em> even a bit faster!</p><p>How is that possible? If you look in the numbers carefully, you can find that in both tests the performance of the <em>equalsIgnoreCase</em> is very close. What actually had changed, is the execution time of the <em>equals(param.toLowerCase())</em>. So, we have either <em>equals </em>or <em>toLowerCase </em>method improved in Java 11.</p><p>(I did a small investigation. Looks like the main difference in performance between Java 8 and Java 11 comes from the <em>toLowerCase()</em> method. It was like 70% refactored).</p><p>Here are some conclusions from the above results:</p><ul><li>Use Java 11 to get the free improvements even without any code changes</li><li>Go with <em>equals()</em> when possible. For example, in case you have control over the data or the server API, you can do <em>toLowerCase()</em> on the UI or you can require the parameters of the API to be case sensitive. We do it a lot in <a href="https://blynk.io/">Blynk</a></li><li>When you don’t have control over the input, choose <em>equalsIgnoreCase()</em> over <em>equals(param.toLowerCase()).</em> It doesn’t allocate unnecessary objects, has a fast path when the string length doesn&#39;t match and it’s still faster on Java 8</li></ul><p>Fortunately, this time spring and hibernate did much better. I didn’t find any <em>equals(param.toLowerCase())</em> patterns. Looks like they already fixed that.</p><h3>startsWith</h3><p>Let’s look at another use case:</p><pre>if (url.toLowerCase().startsWith(“http”)) {</pre><pre>}</pre><p>or</p><pre>if (url.substring(0, 4).equalsIgnoreCase(“http”)) {</pre><pre>}</pre><p>Again, this is a valid, commonly used code. It’s pretty clear what it’s doing. But we can do better. Let’s rewrite it with the less known method <a href="https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/lang/String.html#regionMatches(boolean,int,java.lang.String,int,int)"><em>String.regionMatches</em></a> that we saw in the <em>String.equalsIgnoreCase:</em></p><pre>if (url.regionMatches(true, 0, &quot;http&quot;, 0, &quot;http&quot;.length())) {<br>}</pre><p>Now, let’s prove it’s actually faster:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca087432b1847a4af2b6082cf7cfacc6/href">https://medium.com/media/ca087432b1847a4af2b6082cf7cfacc6/href</a></iframe><p>Note: I also tried Apache Commons Lang 3 <em>StringUtils.startsWithIgnoreCase()</em> method, but it was slower than the Java version. So I excluded it for simplicity.</p><p>Results (lower score means faster):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e014425b891a22e98ff8962cfc69972/href">https://medium.com/media/2e014425b891a22e98ff8962cfc69972/href</a></iframe><p>So, for all cases the <em>String.regionMatches</em> wins with 50–400% difference to the closest competitor.</p><p>The only downside of the <em>regionMatches</em> is that it’s not very self-descriptive, has 5 parameters and it’s hard to see what method does if you aren’t used to it. However, you can add a utility method here, like this:</p><pre>static boolean startsWithIgnoreCase(String url, String param) {<br>    return url.regionMatches(true, 0, param, 0, param.length());<br>}</pre><p>And here again, spring and hibernate did great. Only one or two similar code constructions. But we have other sources of the code.</p><p>Let’s search for similar code in the GitHub:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*rWXcGoq3UKlvdHNuCfICGg.png" /></figure><p>A lot of slow code out there! It could have been worse.</p><p>Have you checked your code already?</p><h3>Conclusion</h3><ul><li>Use Java 11</li><li>Always go with <em>String.equals()</em> over <em>String.equalsIgnoreCase()</em></li><li>If you can’t use <em>String.equals(), </em>use<em> String.equalsIgnoreCase()</em> instead of the <em>equals(toLowerCase())</em> combination</li><li>Always choose <em>String.regionMatches()</em> over alternatives (3-d party library methods included) like <em>toLowerCase().startsWith()</em></li></ul><p>Here is <a href="https://github.com/doom369/java-micro-optimizations">source code</a> of benchmarks, so you can try it yourself.</p><p>Thank you for your attention and stay tuned.</p><p>The next post: <a href="https://medium.com/javarevisited/micro-optimizations-in-java-good-nice-and-slow-enum-261e6f77bd2e?source=friends_link&amp;sk=2efd362f40b01c300b09f425d57a9bb0">Micro optimizations in Java. Good, nice and slow Enum</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea25dfb03f95" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/micro-optimizations-in-java-string-equalsignorecase-ea25dfb03f95">Micro optimizations in Java. String.equalsIgnoreCase()</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Micro optimizations in Java. String.equals()]]></title>
            <link>https://medium.com/javarevisited/micro-optimizations-in-java-string-equals-22be19fd8416?source=rss-acd4d4d667cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/22be19fd8416</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[optmization]]></category>
            <category><![CDATA[string]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[performance]]></category>
            <dc:creator><![CDATA[Dmytro Dumanskiy]]></dc:creator>
            <pubDate>Tue, 28 Jul 2020 16:09:32 GMT</pubDate>
            <atom:updated>2020-08-06T18:02:26.205Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1jjyaWuHTWxMAUAL9AuqEw.png" /></figure><p>Hello everybody, my name is Dmytro Dumanskiy, I’m a CTO and Co-Founder at <a href="https://blynk.io/">Blynk</a>, an Internet of Things platform for businesses. We work hard on making it simple for businesses to connect their electronic devices to the Internet and build white-label apps to monitor and control them remotely. This is my first article in English, so please excuse me for any mistakes.</p><p>In the early days of our product, we had to optimize our back-end infrastructure, again and again, to spend less on the servers. Here is a short background of the loads we are working with right now in our public cloud:</p><ul><li>~80k requests per seconds (~8k req-sec per CPU with 40% utilization)</li><li>~50k hardware connected to the cloud every second</li><li>~350k MAU</li><li>150$ monthly maintenance cost</li></ul><p>With this post, I’m starting a series of articles dedicated to Java micro optimizations. By micro optimizations I mean small, almost invisible, tiny changes within popular Java code constructions that affect the performance of your code.</p><p>In most cases, micro optimizations won’t get you a whole lot of performance boost (you should focus on architecture, algorithms, and data structures for that in the first place). However, in some hot code sections, you can get visible performance improvements. I’ll keep my examples as simple as possible and my posts as short as possible with minimum blah-blah so you don’t get bored.</p><p>I believe this article will be useful for every Java developer.</p><p>So, let’s get started.</p><p><strong>(Please consider all the below code from the point of performance)</strong></p><p><strong>(Please do not focus on numbers, this is just a metric to prove the point)</strong></p><h3>Empty String</h3><p>Let’s look at this basic code:</p><pre><em>if (s != null &amp;&amp; s.equals(“”)) {</em></pre><pre><em>}</em></pre><p>or another “tricky” code to avoid <em>null</em> check:</p><pre><em>if (“”.equals(s)) {</em></pre><pre><em>}</em></pre><p>What is wrong here?</p><p>At first glance, it looks like a correct code. However, if we think about performance, it is not the best choice. Let’s change our approach a bit and use the <em>String.isEmpty()</em> method instead :</p><pre><em>if (s != null &amp;&amp; s.isEmpty()) {</em></pre><pre><em>}</em></pre><p>Let’s check it with a <a href="https://openjdk.java.net/projects/code-tools/jmh/">JMH</a> benchmark:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a2c48b0ccc6ea220e3421098afc49f3/href">https://medium.com/media/6a2c48b0ccc6ea220e3421098afc49f3/href</a></iframe><p>Results (lower score means faster):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/55bf896c43ea9fc3bfbff519d663642e/href">https://medium.com/media/55bf896c43ea9fc3bfbff519d663642e/href</a></iframe><p><em>OpenJDK Runtime Environment (build 11.0.7+10-post-Ubuntu-2ubuntu218.04)</em></p><p>Now, our new code is ~20–40% faster depending on the input string param.</p><p>It is not hard to see where this difference in performance comes from after we look at the <em>String.equals()</em> method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8550776418bb680bd5c5e118507798bd/href">https://medium.com/media/8550776418bb680bd5c5e118507798bd/href</a></iframe><p>Operator <em>instanceOf</em>, class casting, 3 if statements, and all this is just to start the check if the string is actually empty. Now compare it with <em>String.isEmpty()</em>:</p><pre>public boolean isEmpty() {</pre><pre>    return value.length == 0;</pre><pre>}</pre><p>Actually, we don’t need a benchmark here to prove <em>isEmpty()</em> is faster, but it’s interesting to understand just how much faster it could be — 1%, 10%, 100%?</p><p>What do these results tell us? Always use <em>isEmpty()</em> instead of <em>“”.equals(). </em>It will save you a few CPU cycles. This change is so simple! Also, there is one more, less obvious benefit. <em>isEmpty()</em> generates less byte code, so your compiler has more options for inlining. That’s always good for performance.</p><p>In some cases, the input string could be <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#intern%28%29">interned</a> and the <em>“”.equals(s) </em>performance would be similar to the <em>isEmpty()</em> method when <em>s == “”</em>. However, in real-life applications, this is not the case due to non controlled input.</p><p><em>“Okay, I’m an experienced engineer and have been using isEmpty() since it was added in Java 6. My code is fast”, </em>you would say. True, but also you’re using dozens of different libraries and frameworks.</p><p>Let’s look at one of the most popular ones, the Spring framework:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5kJrJuPOUaV8Ra3hSq9fxA.png" /></figure><p>Or Hibernate:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/0*yyJlerS-l1-5HP9a" /></figure><p>Or IntelliJ Idea, where these screenshots are from:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/0*7snHrVvIoU5ofXwJ" /></figure><p>You got the point… And this is in the top frameworks with hundreds of contributors. I wonder how many of these you have in your own code.</p><h3>One char equals</h3><p>Now, let’s consider a slightly different example. In case you are or have been working with web servers, you must have seen these lines of code:</p><pre><em>“/”.equals(url)</em></pre><p>or</p><pre><em>url.equals(“/”)</em></pre><p>What is wrong here?</p><p>I bet you can find this code on every web server. Here it is in Spring-web:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*P-5Zl9zJEBQIX-XW" /></figure><p>The problem here is the same as in the above example, specifically the <em>String.equals()</em> method. It is too generic. And we need only one char check. Unfortunately, the <em>String</em> class doesn’t have the <em>equals(char c)</em> method, so we have to deal with the string.</p><p>Okay, so what can we do? Let’s make a simple, clear, and specialized version of the <em>equals(String s)</em> but for one char:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc47a25b20a28078f9299440d58ba8ce/href">https://medium.com/media/fc47a25b20a28078f9299440d58ba8ce/href</a></iframe><p>Results (lower score means faster):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/482c636a3cb2eee7f409ae759387c32c/href">https://medium.com/media/482c636a3cb2eee7f409ae759387c32c/href</a></iframe><p>So, what do we have here? A 50% better performance for an “/” string and a 10% better performance for the other strings. Not much, but still faster.</p><p>The point here is that typical web servers have to handle this check on every request.</p><p>I know, for many of you these examples are super obvious. However, I see these problems in every library I use. It’s time to fix that.</p><p>Phew… That’s it for now. Hope you like it and it’s helpful.</p><h3>Conclusion</h3><ul><li>Always use <em>String.isEmpty()</em> instead of <em>“”.equals(s)</em> or <em>s.equals(“”)</em></li><li>For hot paths use a specialized version of <em>String.equals(String s)</em> - <em>equals(char c)</em></li></ul><p><a href="https://github.com/doom369/java-micro-optimizations">Source code</a> of benchmarks, so you can try it yourself.</p><p>Thank you for your attention and stay tuned.</p><p>P. S. By the way, in case you wanted to contribute to open-source projects and never had a good starting point — this is it. A simple change that can speed up millions of servers out there, even if only by a tiny bit.</p><p>Then next article is ready —<a href="https://medium.com/@ddumanskiy/micro-optimizations-in-java-string-equalsignorecase-ea25dfb03f95?source=friends_link&amp;sk=28001856b9085e3c927de376298323fd"> Micro optimizations in Java. String.equalsIgnoreCase()</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22be19fd8416" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/micro-optimizations-in-java-string-equals-22be19fd8416">Micro optimizations in Java. String.equals()</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>