길이 1의 문자열로 반환되는 Java의 문자열에서 첫 번째 문자를 얻는 가장 좋은 방법은 무엇입니까?
다음을 가정하십시오.
String example = "something";
String firstLetter = "";
firstLetter성능에 영향을 줄 수 있는 다음과 같은 할당 방법에 유의해야 할 차이점이 있습니까? 어느 것이 가장 좋으며 그 이유는 무엇입니까?
firstLetter = String.valueOf(example.charAt(0));
firstLetter = Character.toString(example.charAt(0));
firstLetter = example.substring(0, 1);
첫 번째 문자가로 반환되는 이유는 String이것이 Hadoop에서 실행되고 있고 Text유형 에 할당하는 데 문자열이 필요하기 때문 입니다. 예를 들어 다음 과 같이 메서드 에서 firstLetter로 출력됩니다 .keymap()
public class FirstLetterMapper extends Mapper<LongWritable, Text, Text, IntWritable> {
String line = new String();
Text firstLetter = new Text();
IntWritable wordLength = new IntWritable();
@Override
public void map(LongWritable key, Text value, Context context)
throws IOException, InterruptedException {
line = value.toString();
for (String word : line.split("\\W+")){
if (word.length() > 0) {
// ---------------------------------------------
// firstLetter assignment
firstLetter.set(String.valueOf(word.charAt(0)).toLowerCase());
// ---------------------------------------------
wordLength.set(word.length());
context.write(firstLetter, wordLength);
}
}
}
}
substring(0, 1)다음과 같이 성능 이 더 좋습니다.
String example = "something";
String firstLetter = "";
long l=System.nanoTime();
firstLetter = String.valueOf(example.charAt(0));
System.out.println("String.valueOf: "+ (System.nanoTime()-l));
l=System.nanoTime();
firstLetter = Character.toString(example.charAt(0));
System.out.println("Character.toString: "+ (System.nanoTime()-l));
l=System.nanoTime();
firstLetter = example.substring(0, 1);
System.out.println("substring: "+ (System.nanoTime()-l));
산출:
String.valueOf: 38553
Character.toString: 30451
substring: 8660
간단히 말해서, 그것은 아마도 중요하지 않을 것입니다. 가장 멋지게 보이는 것을 사용하십시오.
Oracle의 Java 7 JDK를 사용하는 더 긴 대답은 JLS에 정의되어 있지 않기 때문입니다.
String.valueOf또는 Character.toString동일한 방식으로 작동하므로 더 좋아 보이는 것을 사용하십시오. 사실, Character.toString단순히 String.valueOf( source ) 를 호출합니다 .
따라서 질문은 또는 String.substring. 여기서도 그다지 중요하지 않습니다. String.substring원래 문자열을 사용 char[]하므로보다 적은 하나의 객체를 할당합니다 String.valueOf. 이렇게하면 GC (메모리 누수 일 수 있음)에 한 문자 문자열을 사용할 수있을 때까지 원래 문자열이 GC되는 것을 방지 할 수 있지만, 귀하의 예에서는 각 반복 후 GC에 둘 다 사용할 수 있으므로 그렇지 않습니다. 상관 없습니다. 저장하는 할당도 중요하지 않습니다. a char[1]는 할당 비용이 저렴하고 수명이 짧은 객체 (1 문자 문자열)도 GC에 저렴합니다.
세 가지를 측정 할 수있을만큼 충분히 큰 데이터 세트가 있다면 substring아마도 약간의 우위를 줄 것입니다 . 정말 경미합니다. 그러나 "만약 측정 가능하다면"에는이 대답에 대한 진정한 핵심이 포함되어 있습니다. 세 가지를 모두 시도하고 어느 것이 가장 빠른지 측정하는 것이 어떻습니까?
String whole = "something";
String first = whole.substring(0, 1);
System.out.println(first);
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import java.util.concurrent.TimeUnit;
@State(Scope.Thread)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5, time = 1)
@Fork(value = 1)
@Measurement(iterations = 5, time = 1)
public class StringFirstCharBenchmark {
private String source;
@Setup
public void init() {
source = "MALE";
}
@Benchmark
public String substring() {
return source.substring(0, 1);
}
@Benchmark
public String indexOf() {
return String.valueOf(source.indexOf(0));
}
}
결과 :
+----------------------------------------------------------------------+
| Benchmark Mode Cnt Score Error Units |
+----------------------------------------------------------------------+
| StringFirstCharBenchmark.indexOf avgt 5 23.777 ? 5.788 ns/op |
| StringFirstCharBenchmark.substring avgt 5 11.305 ? 1.411 ns/op |
+----------------------------------------------------------------------+
import java.io.*;
class Initials
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s;
char x;
int l;
System.out.print("Enter any sentence: ");
s=br.readLine();
s = " " + s; //adding a space infront of the inputted sentence or a name
s = s.toUpperCase(); //converting the sentence into Upper Case (Capital Letters)
l = s.length(); //finding the length of the sentence</span>
System.out.print("Output = ");
for(int i=0;i<l;i++)
{
x = s.charAt(i); //taking out one character at a time from the sentence
if(x == ' ') //if the character is a space, printing the next Character along with a fullstop
System.out.print(s.charAt(i+1)+".");
}
}
}
'program story' 카테고리의 다른 글
| 채널의 요소 수 (0) | 2020.11.11 |
|---|---|
| 정적 const와 const의 차이점은 무엇입니까? (0) | 2020.11.11 |
| GitHub 위키에서 어떤 종류의 목차를 어떻게 만듭니 까? (0) | 2020.11.11 |
| Bootstrap 3에서 기둥을 쌓을 때 수직 공간 (0) | 2020.11.11 |
| TeamCity에서 배포 한 내 nuget 패키지로 디버그하는 방법은 무엇입니까? (0) | 2020.11.11 |