MongoDB Java API: put() vs append()
I am new to mongo开发者_StackOverflow中文版db 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!
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...
精彩评论