java - Is Objects.requireNonNull less efficient than the old way? -
since jdk 7 i've been happily using method introduced reject null
values passed method cannot accept them:
private void somemethod(sometype pointer, sometype anotherpointer) { objects.requirenonnull(pointer, "pointer cannot null!"); objects.requirenonnull(anotherpointer, "anotherpointer cannot null!"); // rest of method }
i think method makes tidy code easy read, , i'm trying encourage colleagues use it. 1 (particularly knowledgeable) colleague resistant, , says old way more efficient:
private void somemethod(sometype pointer, sometype anotherpointer) { if (pointer == null) { throw new nullpointerexception("pointer cannot null!"); } if (anotherpointer == null) { throw new nullpointerexception("anotherpointer cannot null!"); } // rest of method }
he says calling requirenonnull
involves placing method on jvm call stack , result in worse performance simple == null
check.
so question: there evidence of performance penalty being incurred using objects.requirenonnull
methods?
let's @ implementation of requirenonnull
in oracle's jdk:
public static <t> t requirenonnull(t obj) { if (obj == null) throw new nullpointerexception(); return obj; }
so that's very simple. jvm (oracle's, anyway) includes optimizing two-stage just-in-time compiler convert bytecode machine code. inline trivial methods if can better performance way.
so no, not slower, not in meaningful way, not anywhere matter.
so question: there evidence of performance penalty being incurred using
objects.requirenonnull
methods?
the evidence matter performance measurements of your codebase, or of code designed highly representative of it. can test decent performance testing tool, unless colleague can point real-world example of performance problem in codebase related method (rather synthetic benchmark), i'd tend assume , he/she have bigger fish fry.
as bit of aside, noticed sample method private
method. code team writing calls directly. in situations, might @ whether have use case assertions rather runtime checks. assertions have advantage of not executing in "released" code @ all, , being faster either alternative in question. there places need runtime checks, @ gatekeeping points, public methods , such. fwiw.
Comments
Post a Comment