program tip

개발자가 먼저 가독성이나 성능을 목표로해야합니까?

radiobox 2020. 10. 20. 07:31
반응형

개발자가 먼저 가독성이나 성능을 목표로해야합니까?


종종 개발자는 문제를 해결할 수있는 두 가지 가능한 방법 중 하나를 선택해야합니다. 하나는 관용적이고 읽기 쉬운 방법이고 다른 하나는 덜 직관적이지만 더 나은 성능을 제공 할 수 있습니다. 예를 들어, C 기반 언어에서는 숫자에 2를 곱하는 두 가지 방법이 있습니다.

int SimpleMultiplyBy2(int x)
{
    return x * 2; 
}

int FastMultiplyBy2(int x)
{
    return x << 1;
}

첫 번째 버전은 기술 및 비 기술 독자 모두에게 더 간단하지만 비트 이동이 곱셈보다 더 간단한 작업이기 때문에 두 번째 버전이 더 잘 수행 될 수 있습니다. (지금은 컴파일러의 옵티마이 저가이를 감지하고 최적화하지 않을 것이라고 가정 해 보겠습니다.

개발자로서 초기 시도로 어느 것이 더 좋을까요?


하나 놓쳤습니다.

첫 번째 코드는 정확성을위한 것이고 그 다음은 명확성을위한 것입니다 (물론 둘은 종종 연결되어 있습니다!). 마지막으로 실제로 필요한 실제 경험적 증거가있는 경우에만 최적화를 살펴볼 수 있습니다. 조기 최적화는 정말 악합니다. 최적화에는 거의 항상 시간, 명확성, 유지 보수 비용이 듭니다. 당신은 그것으로 가치있는 것을 구입하고 있는지 확인하는 것이 좋습니다.

좋은 알고리즘은 거의 항상 현지화 된 튜닝보다 우수합니다. 정확하고 명확하며 빠른 코드를 가질 수없는 이유는 없습니다. 하지만 '빠름'에 초점을 맞추기 시작하면 불합리하게 운이 좋을 것입니다.


IMO는 성능이 측정되고 더 빠른 버전이 필요할 때까지 분명하게 읽을 수있는 버전입니다.


Don Knuth 에게서 가져옵니다.

조기 최적화는 프로그래밍에서 모든 악 (또는 적어도 대부분)의 근원입니다.


가독성 100 %

컴파일러가 "x * 2"=> "x << 1"최적화를 수행 할 수없는 경우 새 컴파일러를 사용하십시오!

또한 프로그램 시간의 99.9 %는 사용자 입력, 데이터베이스 쿼리 및 네트워크 응답을 기다리는 데 소비됩니다. 20 bajillion 시간을 여러 번 수행하지 않는 한 눈에 띄지 않을 것입니다.


주어진 예에서 99.9999 %의 컴파일러는 두 경우 모두 동일한 코드를 생성합니다. 내 일반적인 규칙을 설명합니다. 먼저 가독성과 유지 관리를 위해 작성하고 필요할 때만 최적화하십시오.


확실히 가독성. 누군가가 불평하지 않는 한 속도에 대해 걱정하지 마십시오


가독성.

성능을위한 코딩에는 고유 한 과제가 있습니다. Joseph M. Newcomer가 말했습니다.

최적화는 중요한 경우에만 중요합니다. 그것이 중요 할 때는 매우 중요하지만 그것이 중요하다는 것을 알기 전까지는 많은 시간을 낭비하지 마십시오. 그것이 중요하다는 것을 알고 있더라도 그것이 중요한 위치를 알아야합니다. 성능 데이터가 없으면 무엇을 최적화해야할지 알 수 없으며 아마도 잘못된 것을 최적화 할 것입니다.

결과는 모호하고 작성하기 어렵고 디버그하기 어렵고 문제를 해결하지 못하는 코드를 유지하기가 어렵습니다. 따라서 (a) 소프트웨어 개발 및 소프트웨어 유지 관리 비용이 증가하고 (b) 성능에 전혀 영향을 미치지 않는다는 이중 단점이 있습니다.


가독성. 최적화 할 시간은 베타 테스트를 할 때입니다. 그렇지 않으면 시간을 보내는 데 필요한 것이 무엇인지 결코 알 수 없습니다.


나는 가독성을 우선으로 할 것입니다 . 오늘날 우리가 가지고있는 최적화 된 언어와 엄청나게로드 된 머신을 고려할 때 우리가 읽을 수있는 방식으로 작성하는 대부분의 코드는 제대로 작동 할 것입니다.

매우 드문 시나리오에서 성능 병목 현상이 발생할 것이라고 확신하고 (과거의 나쁜 경험에서 비롯된 것일 수 있음) 성능에 큰 이점을 줄 수있는 이상한 트릭을 찾았습니다. 그. 그러나 코드 조각을 잘 주석 처리해야 더 읽기 쉽게 만들 수 있습니다.


이 논쟁에서 자주 간과되는 요소는 프로그래머가 읽기 어려운 코드를 탐색하고 이해하고 수정하는 데 걸리는 추가 시간입니다. 프로그래머의 시간이 한 시간에 백 달러 이상이라는 것을 고려할 때 이것은 매우 실제적인 비용입니다.
모든 성능 향상은 개발시 직접 추가 비용으로 상쇄됩니다.


설명과 함께 주석을 달면 읽기 쉽고 빠릅니다.

실제로 프로젝트 유형과 성능이 얼마나 중요한지에 따라 다릅니다. 3D 게임을 제작하는 경우 일반적으로 거기에 던져야 할 일반적인 최적화가 많이 있으며, 그렇게하지 않을 이유가 없습니다 (초기에 너무 몰두하지 마십시오). 그러나 당신이 까다로운 일을하고 있다면 그것을 보는 사람이 당신이 까다로운 방법과 이유를 알 수 있도록 주석을 달아 라.


대답은 상황에 따라 다릅니다. 예를 들어 장치 드라이버 프로그래밍이나 게임 개발에서 두 번째 형식은 허용되는 관용구입니다. 비즈니스 애플리케이션에서는 그리 많지 않습니다.

가장 좋은 방법은 다른 개발자가 코드 를 어떻게 수행하는지 확인하기 위해 코드 (또는 유사한 성공적인 애플리케이션)를 살펴 보는 것입니다.


<<를 사용하면 마이크로 최적화가 수행됩니다. 그래서 Hoare의 (너츠가 아닌) 규칙 :

조기 최적화 는 모든 악의 근원입니다.

적용되며 우선 더 읽기 쉬운 버전을 사용해야합니다.

이것은 IMHO가 확장 할 수 없거나 잘 수행 할 수없는 소프트웨어를 설계하기위한 변명으로 종종 오용되는 규칙입니다.


양자 모두. 코드는 둘 다 균형을 이루어야합니다. 가독성 및 성능. 둘 중 하나를 무시하면 프로젝트의 ROI가 망가질 수 있기 때문에 결국 상사에게 중요한 것은 그 전부입니다.

가독성이 좋지 않으면 유지 관리가 어려워지고 유지 관리에 더 많은 리소스가 소비되어 ROI가 낮아집니다.

성능이 좋지 않으면 투자 및 고객 기반이 감소하여 ROI가 낮아집니다.


코드베이스가 클수록 가독성이 중요합니다. 작은 기능을 이해하려고 노력하는 것은 그렇게 나쁘지 않습니다. (특히 예제의 메소드 이름이 단서를 제공하기 때문입니다.) 마침내 코딩을 그만 둔 외톨이 천재가 작성한 우버 코드의 일부에는 그리 좋지 않습니다. 왜냐하면 그는 자신의 능력의 복잡성의 최고점을 보았 기 때문입니다. 당신을 위해 썼고 당신은 결코 그것을 이해하지 못할 것입니다.


코드의 가독성이 걱정된다면 주저하지 말고 주석을 추가하여이 작업을 수행하는 이유와 내용을 상기하십시오.


곱셈 대 bitshift는 것입니다 사소한 최적화 그 이익 옆에 아무것도 . 그리고 지적했듯이 컴파일러가이를 수행해야합니다. 그 외에는이 명령이 실행되는 CPU와 마찬가지로 이득은 무시할 수 있습니다.

반면에 심각한 계산을 수행해야하는 경우 올바른 데이터 구조가 필요합니다. 그러나 문제가 복잡하다면 그 문제를 알아내는 것이 해결책의 일부입니다. 예를 들어, 정렬되지 않은 1000000 개 개체의 배열에서 ID 번호를 검색해보십시오. 그런 다음 이진 트리 또는 해시 맵을 사용하여 재고하십시오.

그러나 n << C와 같은 최적화는 일반적으로 무시할 수 있고 언제든지 변경하기가 쉽습니다. 코드를 읽기 쉽게 만드는 것은 아닙니다.


해결해야 할 작업에 따라 다릅니다. 일반적으로 가독성이 더 중요하지만 처음부터 성능을 생각할 때 여전히 몇 가지 작업이 있습니다. 그리고 최적화 자체가 코드의 충분한 부분을 처음부터 다시 작성해야 할 수도 있기 때문에 모든 것이 완벽하게 작동 한 후에는 프로파일 링 및 최적화를 위해 하루를 보낼 수 없습니다. 그러나 요즘에는 흔하지 않습니다.


항상 최대로 최적화해야하며 성능은 항상 중요합니다. 오늘날 우리가 블로 트웨어를 사용하는 이유는 대부분의 프로그래머가 최적화 작업을 원하지 않기 때문입니다.

그렇긴해도 매끄러운 코딩에 설명이 필요한 곳에 언제든지 주석을 달 수 있습니다.


병목 현상을 모르면 최적화 할 필요가 없습니다. 코드의 해당 부분이 거의 실행되지 않는 경우에만 함수를 매우 효율적으로 만들었을 수 있습니다 (보통 어느 정도 가독성을 떨어 뜨림). 따라서 측정 할 것이있을 때까지 마이크로 최적화 할 수 없으며 가독성을 위해 시작하는 것이 좋습니다. 그러나 전체 아키텍처를 설계 할 때 속도와 이해 가능성을 모두 염두에 두어야합니다. 둘 다 엄청난 영향을 미치고 변경하기 어려울 수 있기 때문입니다 (코딩 스타일 및 방법론에 따라 다름).


소프트웨어 비용의 약 70 %가 유지 관리에있는 것으로 추정됩니다. 가독성은 시스템을보다 쉽게 ​​유지 관리 할 수 ​​있도록하여 수명 동안 소프트웨어 비용을 낮 춥니 다.

There are cases where performance is more important the readability, that said they are few and far between.

Before sacrifing readability, think "Am I (or your company) prepared to deal with the extra cost I am adding to the system by doing this?"


I don't work at google so I'd go for the evil option. (optimization)

In Chapter 6 of Jon Bentley's "Programming Pearls", he describes how one system had a 400 times speed up by optimizing at 6 different design levels. I believe, that by not caring about performance at these 6 design levels, modern implementors can easily achieve 2-3 orders of magnitude of slow down in their programs.


As almost everyone said in their answers, I favor readability. 99 out of 100 projects I run have no hard response time requirements, so it's an easy choice.

Before you even start coding you should already know the answer. Some projects have certain performance requirements, like 'need to be able to run task X in Y (milli)seconds'. If that's the case, you have a goal to work towards and you know when you have to optimize or not. (hopefully) this is determined at the requirements stage of your project, not when writing the code.

Good readability and the ability to optimize later on are a result of proper software design. If your software is of sound design, you should be able to isolate parts of your software and rewrite them if needed, without breaking other parts of the system. Besides, most true optimization cases I've encountered (ignoring some real low level tricks, those are incidental) have been in changing from one algorithm to another, or caching data to memory instead of disk/network.


Readability is the FIRST target.

In the 1970's the army tested some of the then "new" techniques of software development (top down design, structured programming, chief programmer teams, to name a few) to determine which of these made a statistically significant difference.

THe ONLY technique that made a statistically significant difference in development was...

ADDING BLANK LINES to program code.

The improvement in readability in those pre-structured, pre-object oriented code was the only technique in these studies that improved productivity.

==============

Optimization should only be addressed when the entire project is unit tested and ready for instrumentation. You never know WHERE you need to optimize the code.

In their landmark books Kernigan and Plauger in the late 1970's SOFTWARE TOOLS (1976) and SOFTWARE TOOLS IN PASCAL (1981) showed ways to create structured programs using top down design. They created text processing programs: editors, search tools, code pre-processors.

When the completed text formating function was INSTRUMENTED they discovered that most of the processing time was spent in three routines that performed text input and output ( In the original book, the i-o functions took 89% of the time. In the pascal book, these functions consumed 55%!)

They were able to optimize these THREE routines and produced the results of increased performance with reasonable, manageable development time and cost.


Readability first. But even more than readability is simplicity, especially in terms of data structure.

I'm reminded of a student doing a vision analysis program, who couldn't understand why it was so slow. He merely followed good programming practice - each pixel was an object, and it worked by sending messages to its neighbors...

check this out


If there is no readability , it will be very hard to get performance improvement when you really need it.

Performance should be only improved when it is a problem in your program, there are many places would be a bottle neck rather than this syntax. Say you are squishing 1ns improvement on a << but ignored that 10 mins IO time.

Also, regarding readability, a professional programmer should be able to read/understand computer science terms. For example we can name a method enqueue rather than we have to say putThisJobInWorkQueue.


Write for readability first, but expect the readers to be programmers. Any programmer worth his or her salt should know the difference between a multiply and a bitshift, or be able to read the ternary operator where it is used appropriately, be able to look up and understand a complex algorithm (you are commenting your code right?), etc.

Early over-optimization is, of course, quite bad at getting you into trouble later on when you need to refactor, but that doesn't really apply to the optimization of individual methods, code blocks, or statements.


I'd say go for readability.

But in the given example, I think that the second version is already readable enough, since the name of the function exactly states, what is going on in the function.

If we just always had functions that told us, what they do ...


How much does an hour of processor time cost?

How much does an hour of programmer time cost?


IMHO both things have nothing to do. You should first go for code that works, as this is more important than performance or how well it reads. Regarding readability: your code should always be readable in any case.

However I fail to see why code can't be readable and offer good performance at the same time. In your example, the second version is as readable as the first one to me. What is less readable about it? If a programmer doesn't know that shifting left is the same as multiplying by a power of two and shifting right is the same as dividing by a power of two... well, then you have much more basic problems than general readability.

참고URL : https://stackoverflow.com/questions/183201/should-a-developer-aim-for-readability-or-performance-first

반응형