Эмпирические данные на эффектах неизменности?

Чтобы проверить, находится ли мозаика в тени, необходимо отодвинуть прямую линию к источнику света. Если строка пересекает другую мозаику, это занято, то мозаика, которую Вы тестировали, находится в тени. Алгоритмы трассировки лучей делают это для каждого объекта (в Вашей мозаике случая) в представлении.

статья Raytracing о Википедии имеет псевдокод.

16
задан Imagist 29 September 2009 в 15:17
поделиться

8 ответов

I would point to Item 15 in Effective Java. The value of immutability is in the design (and it isn't always appropriate - it is just a good first approximation) and design preferences are rarely argued from a statistical point of view, but we have seen mutable objects (Calendar, Date) that have gone really bad, and serious replacements (JodaTime, JSR-310) have opted for immutability.

5
ответ дан 30 November 2019 в 23:05
поделиться

The biggest advantage of immutability in Java, in my opinion, is simplicity. It becomes much simpler to reason about the state of an object, if that state cannot change. This is of course even more important in a multi-threaded environment, but even in simple, linear single-threaded programs it can make things far easier to understand.

See this page for more examples.

2
ответ дан 30 November 2019 в 23:05
поделиться

Итак, мой вопрос, были ли любые статистические исследования, проведенные на эффекты неизменности в реальном мире code?

Я бы сказал, что ваш профессор просто тупит - не обязательно намеренно или даже плохо. Просто вопрос слишком расплывчатый. Две реальные проблемы с вопросом:

  • «Статистические исследования влияния [x]» на самом деле ничего не значат, если вы не укажете, какие измерения вы ищете.
  • «Реальный мир code "на самом деле ничего не значит, если вы не укажете конкретный домен. Код реального мира включает научные вычисления, разработку игр, движки блогов, автоматические генераторы доказательств, хранимые процедуры, ядра операционной системы и т.д.

Как бы то ни было, способность компилятора оптимизировать неизменяемые объекты хорошо документирована. Вне моей головы:

  • Компилятор Haskell выполняет обезлесение (также называемое сокращенным слиянием), где Haskell преобразует выражение map f. карта g в карта f. g . Поскольку функции Haskell неизменяемы, эти выражения гарантированно производят эквивалентный результат, но вторая функция работает в два раза быстрее, поскольку нам не нужно создавать промежуточный список.
  • Исключение общих подвыражений, где мы могли бы преобразовать x = foo (12); y = foo (12) до temp = foo (12); x = темп; y = temp; возможно только в том случае, если компилятор может гарантировать, что foo является чистой функцией. Насколько мне известно, компилятор D может выполнять подобные замены с использованием ключевых слов pure и immutable . Если я правильно помню, некоторые компиляторы C и C ++ будут агрессивно оптимизировать вызовы этих функций, помеченных как «чистые» (или любое другое эквивалентное ключевое слово).
  • Пока у нас нет изменяемого состояния, достаточно умный компилятор может выполнять линейные блоки кода в нескольких потоках с гарантией, что мы не повредим состояние переменных в другом потоке.

Что касается параллелизма, то подводные камни параллелизма с использованием изменяемого состояния хорошо документированы и не нуждаются в повторном изложении.


Конечно, это все анекдотические свидетельства, но это в значительной степени лучшее, что вы получите. Споры о неизменности и изменчивости - это в значительной степени беспощадное совпадение, и вы не найдете работы, в которой бы делались широкие обобщения вроде «функциональное программирование лучше императивного».

В лучшем случае , вы ». Вероятно, вы обнаружите, что вы можете обобщить преимущества неизменяемого и изменяемого в наборе лучших практик , а не в виде систематизированных исследований и статистических данных. Например, изменчивое состояние - враг многопоточного программирования; с другой стороны, изменяемые очереди и массивы часто легче писать и более эффективны на практике, чем их неизменяемые варианты.

Это требует практики, но со временем вы научитесь использовать правильный инструмент для работы, а не запихивать любимого питомца парадигма в проект.

2
ответ дан 30 November 2019 в 23:05
поделиться

I think your professor's being overly stubborn (probably deliberately, to push you to a fuller understanding). Really the benefits of immutability are not so much what the complier can do with optimisations, but really that it's much easier for us humans to read and understand. A variable that is guaranteed to be set when the object is created and is guaranteed not to change afterwards, is much easier to grok and reason with than one which is this value now but might be set to some other value later.

This is especially true with threading, in that you don't need to worry about processor caches and monitors and all that boilerplate that comes with avoiding concurrent modifications, when the language guarantees that no such modification can possibly occur.

And once you express the benefits of immutability as "the code is easier to follow", it feels a bit sillier to ask for empirical measurements of productivity increases vis-a-vis "easier-to-followness".

On the other hand, the compiler and Hotspot can probably perform certain optimisations based on knowing that a value can never change - like you I have a feeling that this would take place and is a good things but I'm not sure of the details. It's a lot more likely that there will be empirical data for the types of optimisation that can occur, and how much faster the resulting code is.

1
ответ дан 30 November 2019 в 23:05
поделиться
  • Don't argue with the prof. You have nothing to gain.
  • These are open questions, like dynamic vs static typing. We sometimes think functional techniques involving immutable data are better for various reasons, but it's mostly a matter of style so far.
1
ответ дан 30 November 2019 в 23:05
поделиться

What would you objectively measure? GC and object count could be measured with mutable/immutable versions of the same program (although how typical that would be would be subjective, so this is a pretty weak argument). I can't imagine how you could measure the removal of threading bugs, except maybe anecdotally by comparison with a real world example of a production application plagued by intermittent issues fixed by adding immutability.

1
ответ дан 30 November 2019 в 23:05
поделиться

Immutability is a good thing for value objects. But how about other things? Imagine an object that creates a statistic:

Stats s = new Stats ();

... some loop ...
     s.count ();

s.end ();
s.print ();

which should print "Processed 536.21 rows/s". How do you plan to implement count() with an immutable? Even if you use an immutable value object for the counter itself, s can't be immutable since it would have to replace the counter object inside of itself. The only way out would be:

     s = s.count ();

which means to copy the state of s for every round in the loop. While this can be done, it surely isn't as efficient as incrementing the internal counter.

Moreover, most people would fail to use this API right because they would expect count() to modify the state of the object instead of returning a new one. So in this case, it would create more bugs.

0
ответ дан 30 November 2019 в 23:05
поделиться

As other comments have claimed, it would be very, very hard to collect statistics on the merits of immutable objects, because it would be virtually impossible to find control cases - pairs of software applications which are alike in every way, except that one uses immutable objects and the other does not. (In nearly every case, I would claim that one version of that software was written some time after the other, and learned numerous lessons from the first, and so improvements in performance will have many causes.) Any experienced programmer who thinks about this for a moment ought to realize this. I think your professor is trying to deflect your suggestion.

Meanwhile, it is very easy to make cogent arguments in favor of immutability, at least in Java, and probably in C# and other OO languages. As Yishai states, Effective Java makes this argument well. So does the copy of Java Concurrency in Practice sitting on my bookshelf.

0
ответ дан 30 November 2019 в 23:05
поделиться
Другие вопросы по тегам:

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