简体   繁体   English

如何优化以下代码以更好地使用内存?

[英]How can i optimize the following code for better memory usage?

/* package codechef; // don't place package name! */
import java.util.StringTokenizer;
import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */

class Codechef
{

     String func (String s1)
    {
        StringTokenizer st =new StringTokenizer(s1);
        String fina= new String();
            while(st.hasMoreTokens())
            {
                String s= st.nextToken();
                char []ch= s.toCharArray(); 
                int length= ch.length;
                int r=0;
                int i =1;
                while(i<=length/2)
                    {  

                        char temp;
                        temp=ch[i];
                        ch[i]=ch[length-1-r];
                        ch[length-1-r]=temp;
                        r++;
                        i++;
                     }


                String revword=new String(ch);
                fina+=""+revword +" ";

            }

            return(fina);

    }

    public static void main (String[] args) throws java.lang.Exception
    {
        String s1="Tarun is a intern";  
        Codechef c=new Codechef();
        String s2=c.func(s1);
        System.out.println(""+s2);
    }
}

The above code was run on codechef ide i am using 2638 KB of memory .上面的代码是在codechef ide上运行的,我使用的是2638 KB 的内存 Is there any other method I can use to decrease the memory usage?有没有其他方法可以用来减少内存使用量? Or any other optimized method?或者有什么其他优化的方法? I tried using StringBuilder to append as it is mutable still it was giving me same memory usage on code chef.我尝试使用 StringBuilder 进行追加,因为它是可变的,但它仍然给我代码厨师相同的内存使用量。

This question would probably be better on codereview.stackexchange.com but nevertheless, I'll make some comments here.这个问题在 codereview.stackexchange.com 上可能会更好,但尽管如此,我还是会在这里发表一些评论。

Out of the 2638 KB of memory used, I expect the vast majority of that is used by the Java Runtime Environment, rather than directly by your application.在所使用的 2638 KB 内存中,我预计其中的绝大部分是由 Java 运行时环境使用的,而不是直接由您的应用程序使用。 Still you might make a few KB of savings.您仍然可以节省几 KB。 Here's a line-by-line commentary.这是逐行评论。

/* package codechef; // don't place package name! */

No need to keep the above line in your code.无需在代码中保留以上行。

import java.util.StringTokenizer;
import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */

class Codechef
{

     String func (String s1)
    {
        StringTokenizer st =new StringTokenizer(s1);

The documentation of StringTokenizer says this is a legacy class kept for backward compatibility and that newer code should use String.split() instead. StringTokenizer 的文档说这是一个为向后兼容而保留的遗留类,较新的代码应该使用String.split()代替。 This would improve readability, though I doubt it would improve performance or memory usage.这将提高可读性,但我怀疑它会提高性能或内存使用情况。

        String fina= new String();

Why are you using new String() ?你为什么使用new String() Just use "" .只需使用"" By using new String() you are creating a new object, thus wasting a few bytes of memory, when "" refers to an existing object, and is more readable.通过使用new String()您正在创建一个新对象,从而浪费了几个字节的内存,当""引用现有对象时,并且更具可读性。

            while(st.hasMoreTokens())
            {
                String s= st.nextToken();
                char []ch= s.toCharArray(); 
                int length= ch.length;
                int r=0;

It may be slightly more readable to start r at 1 and use length-r instead of length-1-r .r从 1 开始并使用length-r而不是length-1-r可能更具可读性。

                int i =1;

You need to start i at 0, as this is the index of the first character.您需要从 0 开始i ,因为这是第一个字符的索引。

                while(i<=length/2)

It may be more readable to use a for loop.使用for循环可能更具可读性。

                    {  

                        char temp;
                        temp=ch[i];

Why not declare and initialize on the same line?为什么不在同一行声明和初始化? char temp = ch[i];

                        ch[i]=ch[length-1-r];
                        ch[length-1-r]=temp;
                        r++;
                        i++;
                     }


                String revword=new String(ch);
                fina+=""+revword +" ";

There is no need for the ""+ preceding revword.不需要""+前面的revword。 You are creating a new String by doing this (thus wasting memory).您正在通过这样做创建一个新字符串(从而浪费内存)。 But revword is already a string, so no need to append it to a null string.但是revword已经是一个字符串,所以不需要将它附加到一个空字符串。

Appending to a String fina inside a loop costs CPU time (and some memory).在循环内追加到String fina消耗 CPU 时间(和一些内存)。 You should use a StringBuilder instead.您应该改用StringBuilder

Also, if you used StringBuilder you would have been able to copy ch to it directly, without having to create a new String that is a copy of ch .此外,如果您使用StringBuilder您将能够直接将ch复制到它,而无需创建一个新的String ,它是ch的副本。

            }

            return(fina);

Minor nit-pick: no need for parentheses here, as it makes the return keyword look like a method call, which it is not.小问题:这里不需要括号,因为它使return关键字看起来像一个方法调用,而事实并非如此。

    }

By the way, your method adds a " " (space) at the end of the returned string, which is probably not what you want.顺便说一句,您的方法在返回的字符串末尾添加了一个" " (空格),这可能不是您想要的。

    public static void main (String[] args) throws java.lang.Exception
    {
        String s1="Tarun is a intern";  
        Codechef c=new Codechef();
        String s2=c.func(s1);
        System.out.println(""+s2);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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