2012-11-30 38 views
1

例如,可以說我有以下代碼:在Java中,是substring(int k,int y)還是substring(int k)更高效的性能?

String s1 = "foobar"; 
s1 = s1.substring(3); 

請問這代碼少效率比:

String s1 = "foobar"; 
s1 = s1.substring(3, 6); 

我在想,這兩個參數的方法是更高效的性能明智的,因爲單參數方法使用循環遍歷索引直到達到長度。這意味着JVM必須調用length()方法來確定何時停止循環。

但是,兩個參數方法只循環到達到最後一個索引號。

任何人都可以證實或否認我的假設嗎?

編輯: 我真的不明白在源代碼(最後返回語句),但這裏是java String類來源:

public String substring(int beginIndex, int endIndex) { 
    if (beginIndex < 0) { 
     throw new StringIndexOutOfBoundsException(beginIndex); 
    } 
    if (endIndex > count) { 
     throw new StringIndexOutOfBoundsException(endIndex); 
    } 
    if (beginIndex > endIndex) { 
    } 
    return ((beginIndex == 0) && (endIndex == count)) ? this : // I don't understand this part 
     new String(offset + beginIndex, endIndex - beginIndex, value); 
} 
+1

查找到Strings.substring – AlexWien

+2

的源代碼,您可以確認或標杆兩個版本自己否認這一點:) – NPE

+4

不要過早優化 –

回答

10

String.substring()是恆定的時間,它只是提供原始字符串的視圖更小。此外,該版本帶有一個參數只是...委託給一個有兩個:

public String substring(int beginIndex) { 
    return substring(beginIndex, count); 
} 

countString.length()返回的值。選擇哪個版本並不重要,它們都非常快。

- 顯然no longer true自Java 7 update 6開始,但與您的問題無關。

+0

我已經有足夠的一天,否則會給最後兩個字+1。 ;) –

+2

從Java 7 Update 6開始,這不再是真實的。現在支持'char []'總是被複制,使得這個O(n)。 –

+0

@MarkoTopolnik:我很震驚,你能提供一些參考或指針來源代碼(無法找到它在grepcode)?感謝這些信息。 –

1

我不認爲有任何區別。如果你看到String類的源代碼字符串(INT的beginIndex) - 簡單地調用子(的beginIndex,lengthOfTheString)

1
public String substring(int beginIndex, int endIndex) 

稍快是因爲

public String substring(int beginIndex) { 
     return substring(beginIndex, count); 
} 

,這樣你就可以避免一個間接。但它不值得考慮這一點。

0

Java源代碼,substring(beginIndex)將invodke substring(beginIndex, count)

相關問題