charAt() or substring? Which is faster?

后端 未结 6 2393
天命终不由人
天命终不由人 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:44

    Of the two snippets you've posted, I wouldn't want to say. I'd agree with Will that it almost certainly is irrelevant in the overall performance of your code - and if it's not, you can just make the change and determine for yourself which is fastest for your data with your JVM on your hardware.

    That said, it's likely that the second snippet would be better if you converted the String into a char array first, and then performed your iterations over the array. Doing it this way would perform the String overhead once only (converting to the array) instead of every call. Additionally, you could then pass the array directly to the String constructor with some indices, which is more efficient than taking a char out of an array to pass it individually (which then gets turned into a one character array):

    String s = "abcdefg";
    char[] chars = s.toCharArray();
    for(int i = 0; i < chars.length; i++) {
        newFunction(String.valueOf(chars, i, 1));
    }
    

    But to reinforce my first point, when you look at what you're actually avoiding on each call of String.charAt() - it's two bounds checks, a (lazy) boolean OR, and an addition. This is not going to make any noticeable difference. Neither is the difference in the String constructors.

    Essentially, both idioms are fine in terms of performance (neither is immediately obviously inefficient) so you should not spend any more time working on them unless a profiler shows that this takes up a large amount of your application's runtime. And even then you could almost certainly get more performance gains by restructuring your supporting code in this area (e.g. have newFunction take the whole string itself); java.lang.String is pretty well optimised by this point.

提交回复
热议问题