Строка использует для своей выгоды - лучший путь

Используя DayOfWeek был бы способ достигнуть этого:

    DateTime date = DateTime.Now.AddDays(-7);
    while (date.DayOfWeek != DayOfWeek.Monday)
    {
        date = date.AddDays(-1);
    }

    DateTime startDate = date;
    DateTime endDate = date.AddDays(7);
8
задан IAdapter 8 October 2009 в 07:59
поделиться

8 ответов

Производительность равна.

Ваш код копирует char [], вызывающий string.toCharArray () и new String (charArray) .

Код apache в buffer.append (str.substring (1)) и buffer.toString () . В коде apache есть дополнительный экземпляр строки с базовым содержимым char [1, length]. Но это не будет скопировано при создании экземпляра String.

2
ответ дан 5 December 2019 в 11:25
поделиться

Если бы мне пришлось писать библиотеку, я бы попытался убедиться, что у меня есть свой Unicode, прежде чем беспокоиться о спектакль. Совершенно неожиданно:

int len = str.length();
if (len == 0) {
    return str;
}
int head = Character.toUpperCase(str.codePointAt(0));
String tail = str.substring(str.offsetByCodePoints(0, 1));
return new String(new int[] { head }).concat(tail);

(Я бы, наверное, также посмотрел разницу между заголовком и заглавными буквами, прежде чем совершить сделку.)

3
ответ дан 5 December 2019 в 11:25
поделиться

I guess your version will be a little bit more performant, since it does not allocate as many temporary String objects.

I'd go for this (assuming the string is not empty):

StringBuilder strBuilder = new StringBuilder(string);
strBuilder.setCharAt(0, Character.toUpperCase(strBuilder.charAt(0))));
return strBuilder.toString();

However, note that they are not equivalent in that one uses toUpperCase() and the other uses toTitleCase().

From a forum post:

Titlecase <> uppercase
Unicode defines three kinds of case mapping: lowercase, uppercase, and titlecase. The difference between uppercasing and titlecasing a character or character sequence can be seen in compound characters (that is, a single character that represents a compount of two characters).

For example, in Unicode, character U+01F3 is LATIN SMALL LETTER DZ. (Let us write this compound character using ASCII as "dz".) This character
uppercases to character U+01F1, LATIN CAPITAL LETTER DZ. (Which is
basically "DZ".) But it titlecases to to character U+01F2, LATIN CAPITAL
LETTER D WITH SMALL LETTER Z. (Which we can write "Dz".)

character uppercase titlecase
--------- --------- ---------
dz DZ Dz
8
ответ дан 5 December 2019 в 11:25
поделиться

StringBuffer is declared to be thread safe, so it might be less effective to use it (but one shouldn't bet on it before actually doing some practical tests).

1
ответ дан 5 December 2019 в 11:25
поделиться

StringBuilder (начиная с Java 5 и далее) быстрее, чем StringBuffer, если вам не нужно, чтобы он был потокобезопасным, но, как говорили другие, вам нужно проверить, лучше ли это, чем ваше решение в вашем чехол.

1
ответ дан 5 December 2019 в 11:25
поделиться

Have you timed both?

Honestly, they're equivalent.. so the one that performs better for you is the better one :)

0
ответ дан 5 December 2019 в 11:25
поделиться

Not sure what the difference between toUpperCase and toTitleCase is, but it looks as if your solution requires one less instantiation of the String class, while the commons lang implementation requires two (substring and toString create new Strings I assume, since String is immutable).

Whether that's "better" (I guess you mean faster) I don't know. Why don't you profile both solutions?

0
ответ дан 5 December 2019 в 11:25
поделиться

посмотрите на этот вопрос преобразование заголовка . apache FTW.

0
ответ дан 5 December 2019 в 11:25
поделиться
Другие вопросы по тегам:

Похожие вопросы: