charAt() or substring? Which is faster?

后端 未结 6 2394
天命终不由人
天命终不由人 2020-12-15 10:07

I want to go through each character in a String and pass each character of the String as a String to another function.

String s = \"abcdefg\";
for(int i = 0         


        
6条回答
  •  无人及你
    2020-12-15 10:43

    Does newFunction really need to take a String? It would be better if you could make newFunction take a char and call it like this:

    newFunction(s.charAt(i));
    

    That way, you avoid creating a temporary String object.

    To answer your question: It's hard to say which one is more efficient. In both examples, a String object has to be created which contains only one character. Which is more efficient depends on how exactly String.substring(...) and Character.toString(...) are implemented on your particular Java implementation. The only way to find it out is running your program through a profiler and seeing which version uses more CPU and/or more memory. Normally, you shouldn't worry about micro-optimizations like this - only spend time on this when you've discovered that this is the cause of a performance and/or memory problem.

提交回复
热议问题