Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB Java API: put() vs append()

Tags:

java

mongodb

I am new to mongodb and as I going through the tutorial for Java & Mongodb. I notice there is put() and append() for BasicDBObject and I took a look at the API, put() inherit and append() is a built-in for BasicDBObject. Does anyone what is the different, such as speed of access? Thanks!

like image 801
shh Avatar asked Jul 04 '11 10:07

shh


1 Answers

From the BasicDBObject sources:

public BasicDBObject append( String key , Object val ){
    put( key , val );
    return this;
}

put() returns the previous value, if applicable. append() calls put() internally and returns the BasicDBObject instance itself. Essentially, append() is a more fluent interface for put(). It allows you to do something like this:

BasicDBObject o = new BasicDBObject().append("One", 1).append("Two", 2).append("Three", 3);

As far as performance goes, the JVM will supposedly inline methods like append() if they are used frequently enough somewhere. From my experience and quite a bit of profiling, however, that is not always true and you are bound to gain a little bit of speed by using put() directly and saving the JVM the guesswork.

That said, code readability should always be a priority. Just write your code as you feel comfortable, and benchmark/profile afterwards to find any possible optimizations. Premature optimization is a temptation that should be avoided at all costs...

like image 53
thkala Avatar answered Sep 30 '22 03:09

thkala