如何优化以下代码以获得更好的内存使用?

时间:2022-03-01 07:41:30
/* 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. 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.

上面的代码是在codechef上运行的,我正在使用2638 KB的内存。有没有其他方法可以用来减少内存使用量?还是其他任何优化方法?我尝试使用StringBuilder追加,因为它是可变的仍然它给了我相同的内存使用代码厨师。

1 个解决方案

#1


1  

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. Still you might make a few KB of savings. Here's a line-by-line commentary.

在使用的2638 KB内存中,我预计绝大多数内存都是由Java Runtime Environment使用的,而不是由您的应用程序直接使用。你仍然可以节省几KB。这是一个逐行评论。

/* 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. This would improve readability, though I doubt it would improve performance or memory usage.

StringTokenizer的文档说这是为了向后兼容而保留的遗留类,而较新的代码应该使用String.split()。这会提高可读性,但我怀疑它会提高性能或内存使用率。

        String fina= new String();

Why are you using 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.

你为什么使用新的String()?只需使用“”。通过使用新的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.

从1开始r并使用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开始,因为这是第一个字符的索引。

                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];

为什么不在同一行上声明和初始化? 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. 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。您正在通过执行此操作来创建新的String(从而浪费内存)。但是revword已经是一个字符串,所以不需要将它附加到空字符串。

Appending to a String fina inside a loop costs CPU time (and some memory). You should use a StringBuilder instead.

在循环内附加到字​​符串fina会花费CPU时间(和一些内存)。您应该使用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);
    }
}

#1


1  

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. Still you might make a few KB of savings. Here's a line-by-line commentary.

在使用的2638 KB内存中,我预计绝大多数内存都是由Java Runtime Environment使用的,而不是由您的应用程序直接使用。你仍然可以节省几KB。这是一个逐行评论。

/* 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. This would improve readability, though I doubt it would improve performance or memory usage.

StringTokenizer的文档说这是为了向后兼容而保留的遗留类,而较新的代码应该使用String.split()。这会提高可读性,但我怀疑它会提高性能或内存使用率。

        String fina= new String();

Why are you using 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.

你为什么使用新的String()?只需使用“”。通过使用新的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.

从1开始r并使用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开始,因为这是第一个字符的索引。

                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];

为什么不在同一行上声明和初始化? 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. 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。您正在通过执行此操作来创建新的String(从而浪费内存)。但是revword已经是一个字符串,所以不需要将它附加到空字符串。

Appending to a String fina inside a loop costs CPU time (and some memory). You should use a StringBuilder instead.

在循环内附加到字​​符串fina会花费CPU时间(和一些内存)。您应该使用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);
    }
}