During a code review, I got into a discussion about the following method:
private String getAccessToken(HttpServletRequest request) {
Enumeration<String> authHeaders = request.getHeaders("Authorization");
for (; authHeaders.hasMoreElements(); ) {
String header = authHeaders.nextElement();
if (header.startsWith(BEARER_PREFIX)) {
return header.substring(BEARER_PREFIX.length());
}
}
return null;
}
One suggestion was that it would be better from a performance point of view to do this:
String header;
for (; authHeaders.hasMoreElements(); ) {
header = authHeaders.nextElement();
//...
}
in order to avoid allocating the header many times. As a C++ programmer, this surprised me. My assumption would be that the function was doing something like this:
for (; authHeaders.hasMoreElements(); ) {
char* header = authHeaders.nextElement();
//...
}
I.e. header is a stack variable that points to something on the heap and that no allocation would need to be done. But I must admit that I know C/C++ better than I do Java, especially when it comes to what guarantees the language makes about when allocation occurs.
Does moving the declaration of the string variable outside of the loop matter one way or the other?