简体   繁体   中英

The performance impact of use System.getenv() in java

I have a REST web service in java built with jersey and for security reasons I would like to save in the OS environment variables the parameters of the method: DriverManager.getConnection(); . Url, username and password.

Since every request needs to create his own connection I want to know if so many calls to System.getenv("key"); are a performance problem?

The idea of doing so is from this article: http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/java-rds.html#java-rds-javase

Would be a better option to have something like this:

public class EnvironmentHelper {
    static final String URL;
    static final String USERNAME;
    static final String PASSWORD;

    static {
        URL = System.getenv("URL");
        USERNAME = System.getenv("USERNAME");
        PASSWORD = System.getenv("PASSWORD");
    }
}

This way I only load the variables once, right? No matter how many requests I receive.

System.getEnv(name)转换为ProcessEnvironment.getEnv ,它实际上是对HashMap的查找(ProcessEnvironment是HashMap的扩展)。此HashMap加载在运行于类初始化的静态块中,因此查找起来非常快是O(1)的可能性很高。

I doubt that calls to getenv would pose a larger performance issue in comparison to creating a new connection per request, but I believe it will be the best if the problem is approached with the static loading approach you use above. This eliminates the task of searching the environment list for each new connection.

According to the operating system manual for the getenv function , it does need to search the environment list to find the value, but from my C knowledge I know that this requires no syscalls as the environment variables are copied to the program.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM