Monday, June 04, 2018

Fast string concatenation with Groovy

String concatenation is one of most used functions when coding. With Groovy, there are quite a few approaches. This article will focus on different operators. The code to evaluate the performance is given below.
@Grab('com.googlecode.gbench:gbench:0.3.0-groovy-2.0')
import gbench.*

List turns = ((0..1000) as List)*.toString()
new BenchmarkBuilder().run( measureCpuTime:false ) {
   'Dynamic typing <<=' {
    def nums = ""
    turns.each{nums <<= it}
  }
  
  'Dynamic typing +=' {
    def nums = ""
    turns.each{nums += it}
  }
  
  'Static Typing <<=' {
    String nums = ""
    turns.each{nums <<= it}
  }
  
  'Static Typing +=' {
    String nums = ""
    turns.each{nums += it}
  }
}.prettyPrint()
The results are quite interesting. See below.
Options
=======
* Warm Up: Auto 
* CPU Time Measurement: Off

Dynamic typing <<=   52838
Dynamic typing +=   711659
Static Typing <<=   386825
Static Typing +=    647186
To achieve the best performance, we need to use def to declare a String variable, and use the compound operator <<= to perform the concatenation.

Tuesday, May 22, 2018

Groovy double blade: safe navigation operator

In groovy, safe navigation operator is a very cool feature. It helps avoid NullPointerException. However, when using it, need to be careful and avoid something like
list?.size()++
There is no issue for the first part list?.size() at all, the safe navigation operator does it job and helps avoid NullPointerException. The issue is the ++ part. Suppose list is null, list?.size() will also be null. Then null++ will generate an error
java.lang.NullPointerException: Cannot invoke method next() on null object”.


Saturday, September 30, 2017

Portable water storage - best pet food bin

I was in the market for a dog food container. For this container, one of the main requirements was that it should meet human food grade standards, such as BPA free if the material was plastic, lead free if painted.

Bought a tin with a lid that was specially made for pet food. However, on the second day, ants occupied the tin. So I had to return it. Not quite sure what to buy for dog biscuits, then an idea suddenly popped up, why did I need to focus on pet products? Why not try to find something that was not specially designed for pets, but fitted the purpose?

After a bit search on the hardware shop website, I found one product that was perfect portable water storage with wide mouth: airtight and safe. I ended buying a water storage drum for dog biscuits and it worked well.

Think the problem from another dimension and it may find a better solution.