Saturday, 23 July 2016

Referendum petition data examined

You may have noticed that on 23rd June 2016 the UK held a referendum about whether to remain as a member of the European Union.

When the result didn't go quite the way they wanted, some people participated in an online petition with the goal of having parliament consider re-running the referendum to try to obtain a more significant resulting margin.

Link to petition

The apparent popularity of the petition attracted attention on social and conventional media, so I decided to take a look at the data.

There isn't a lot of information that is exposed, basically a breakdown of numbers by country of residence and a breakdown of numbers by constituency.

By loading the data into an application and sorting it and printing it out I noticed something conspicuous - Vatican City showing up as one of the most popular countries of residence.

Hold on, isn't that one of the least populated countries in the world?

Sure enough, the numbers involved exceeded the public stats of the total population - that literally didn't add up.

Myself and a few others flagged this up on Twitter, so the relevant parties did some checks and figured out how to filter out dodgy data and block later attempts at automated contributions.

My code is available on github.  By looking into the Git history you can see for yourself how the data for country counts changed over time.

Petition Analysis github repo

The code for the petition site itself (not by me) is also on GitHub:

https://github.com/alphagov/e-petitions

Tuesday, 19 January 2016

A post about a post - Java performance for obtaining an array from a Collection

Avid readers may recall that a while back I posted something about creating StringBuilders with the correct initial size to avoid wasted memory allocation and subsequent garbage collection.

Today I came across a blog post that covered a similar topic - creating an array from a Collection - but analysing why advice that had become conventional wisdom may no longer be valid.

It goes a little deeper than my day to day work requires me to understand, but I think it is well worth a read.

http://shipilev.net/blog/2016/arrays-wisdom-ancients/

I'm now contemplating finally getting around to using JMH to evaluate whether my approach to StringBuilders is sensible or programming by superstition.

Monday, 3 August 2015

Continuous improvement

Every few years I like to take a couple of weeks out of the working world to learn about techniques and technologies that are approaching the mainstream.

When I first moved to London back in 2008 I had to learn all about Spring and Hibernate as the local job market was mainly fixated on those technologies.

After the recession cooled down a bit I found my way into a development role based on Hybris - an e-commerce system held together by Spring.

Fast forward to 2012, before joining Springer I dabbled in accessing some youtube APIs to see what would be involved in establishing a degrees of separation relationship between music videos via their related videos.  That was a bit of fun and gave me some insight into some simple performance optimisation options in distributed systems:
  • divide the work up and allocate it to a pool of workers
  • have the workers share a small piece of information to prevent duplication of effort (checking videos that had already been visited).
At around the same time I took an interest in nosql databases.  After attending the inaugural London Data Bar meetup group, I won a ticket to a two day hands on NoSQL databases conference which gave me a chance to dabble with neo4j and MongoDB.

For 2015 I'm taking a dabble in open source products, seeing how they work, contributing some code and improving some documentation along the way.

Do drop-outs have an advantage?

Since starting my quest for a new job I've started to notice that the technical interview process often involves some aspect of computer science that I learnt in my first or second year of university.

Twenty years is a long time to stretch my memory back, so I'm going to have to do an online refresher course and / or some reading to keep myself competitive with the recent graduates - where by recent I mean people who have graduated in the last 10 years or so.

Actually, I remember a guy from my class who was getting good grades but decided to leave university without graduating - I think someone in that situation would excel in these technical interviews.

Tuesday, 21 July 2015

Java 8 Lambda overhead

Intro

This is a follow-up to an earlier post where I was speculating that Java's Just In Time compilation may have been causing significant performance differences when some code was being exercised more than one or two times.

Here is a snippet of the code which I would like to focus on:

int anIndex = Collections.binarySearch(sorted, target, 
(o1, o2) -> o1.compareTo(o2)
);

The title of this post should have given away that the lambda expression made the performance take a hit until something kicked in and probably replace the lambda setup in each loop iteration with a single instance.

Alternatives

Comparator intComparator = Integer::compareTo;
int anIndex = Collections.binarySearch(sorted, target, intComparator);

Also uses some Java 8 magic and performs slowly.

Comparator intComparator = new Comparator() {
    @Override    public int compare(Integer o1, Integer o2) {
        return o1.compareTo(o2);    }
};int anIndex = Collections.binarySearch(sorted, target, intComparator);

Doesn't use any lambda expressions and performs quickly.

The final, slightly embarrassing example:

int anIndex = Collections.binarySearch(sorted, target);

So, I didn't even need to define the method for the comparison.

The micro benchmarking trap

JVM Compilation Magic

(Updated - corrected code sample to include actual call to indexOf, which I only noticed after tweeting about this.)

A better indexOf for a sorted ArrayList

I'm in the process of brushing up on my knowledge of the Java Collections API at the moment.  When I came across indexOf(Object object) in ArrayList I decided to see how it works.

Although Lists in Java preserve order they cannot assume their contents will be in a particular order.  So in indexOf(myObject) on a List the safest way to guarantee that the index of the first match that exists will be returned is by starting from the head of the list and iterating through the tail.

As an exercise for myself, I decided to compare the performance of indexOf against a slightly tweaked binary search for when the elements of the list are known to be in a sorted order.

The Collections class provides a binarySearch static method which returns the index of an Object in a List - so the majority of the work has already been done for us.

The tweak that I mentioned earlier is that my List can contain duplicates.  So, once the binarySearch has found a match, we still need to check earlier in the List until we can confirm that we have the very first match.

private static void indexOfSortedList() {
    // indexOf is a bit naive, so let's see if a sorted list     // can be made to behave better with binarySearch    ArrayList sorted = new ArrayList<>(50000000);    // Pre-loading randoms    Random random = new Random();    random.setSeed(1337L);    boolean[] randoms = new boolean[20000000];
    for (int b = 0; b < 20000000; b++) {
        randoms[b] = random.nextBoolean();    }

    for (int i = 0; i < 20000000; i++) {
        sorted.add(i);
        // Introducing duplicates at random points        if (randoms[i]) {
            sorted.add(i);        }
    }

    final Integer target = Integer.valueOf(1700000);
    long timeBefore = System.currentTimeMillis();    int anIndex = Collections.binarySearch(sorted, target,            (o1, o2) -> o1.compareTo(o2)
    );
    // We treat anIndex as starting position and move backwards    // until we establish the first instance    while (anIndex > 0 && sorted.get(anIndex - 1).equals(target)) {
        anIndex--;    }
    System.out.println("Duration binary approach " + 
            (System.currentTimeMillis() - timeBefore));    System.out.println("binarySearch value: " + anIndex);
    long timeBeforeIndexOf = System.currentTimeMillis();    int indexOfValue = sorted.indexOf(target);    System.out.println("Duration indexOf " + 
            (System.currentTimeMillis() - timeBeforeIndexOf));    System.out.println("Index of value: " + indexOfValue);}

The computer scientists amongst you should appreciate how a binary search will involve far fewer operations than the linear search that indexOf is based on.

Would it surprise you to find that the indexOf implementation consistently showed a much faster performance?

That was until I scaled up the search space to have 10s of millions of elements to search through, and shifted the match to be quite high in the search space - biasing towards the binarySearch in a very unfair way.

Slightly surprised at this counterintuitive outcome, I went away for lunch and picked up a book: Java Performance : The definitive guide

A section about the JIT compiler gave me a theory to try out - perhaps this code wasn't being compiled beyond byte code because it was only being run once.

Modifying the setup to loop around calling the method showed numbers that would reinforce that theory.  After the first iteration the tweaked binarySearch performed faster than the indexOf call.

Pre-allocating for capacity

Within the same code you may have noticed that I chose to pre-initialise the capacity of the ArrayList.  This is a habit that I got into when want to reduce waste in memory allocation.

Some code that I have deleted from the example above was measuring the performance of the calls to populate the ArrayList.

I observed that specifying the capacity in advance resulted in slower insertion - even though the code for setting up the capacity was not included in the calls to be measured.

When I changed the code to have multiple calls to the method I observed that the first pass through had poor performance around 11s, but the next few calls dropped down around 4s, and subsequent passes went as low as a few hundred millis but fluctuated back up to around 4s.

Summary

My future approaches to trying some minor performance tweaking change out will not involve single runs, but will take into account how the JVM will actually massage the code into its final working state.