[BOOK] 지구를 위한다는 착각

사람답게 살기 위한 한 달 한 권(2022/02)

환경에 대한 일반적인 통념과는 다른 사실과 근거를 바탕으로 새로운 시각을 제공하는 내용에 흥미가 끌려 선택한 책.

이익 집단에 의한 선택적이고 왜곡된 환경 보호 활동이 아니라 본질에 집중한 생각과 행동이란 무엇일까를 고민하게 만든다.

아래의 내용은 모두 책의 내용에 기반한 것이다.

환경 보호의 대명사 중 하나가 나무이다.

가난한 나라에서 숲이 사라지는 이유는 무엇일까?

가난한 나라에서는 사용할 에너지가 없기 때문이라고 한다.

난방과 취사가 인간의 삶에서 필수적인 요소지만 가난한 나라에서는 난방과 취사에 들어가는 에너지원을 쉽고 저렴하게 구할 수가 없기 때문에 결국 1차 에너지원인 나무가 대량으로 소비되고 있다고 한다.

선진국의 전례에 따라 에너지 밀도가 높은 에너지가 공급되면 저장, 운송의 효율이 높아지고 오염물질을 덜 배출하게 되므로 자연스레 환경 오염 개선에도 효과를 볼 수 있다고 한다.

에너지의 효율이 높은 순서는 다음과 같다.

천연가스 -> 석탄 ->바이오매스(나무)

하지만 한 번에 바이오매스에서 최고 효율의 에너지 단계로 뛰어넘기는 현실적으로 불가능하다.

따라서 제조업을 발전시켜 먼저 나라를 부강하게 하고 밀도 높은 에너지에 투자하여 에너지 공급을 원활하게 하면 오염이 자연스레 줄어들 것이라고 본다.

몇 십년 전만 하더라도 고래를 포획하는 포경 산업이 크게 부흥하여 고래로부터 추출한 원료를 다양한 산업에서 사용하였다.

그러나 현재 고래의 포획이 줄어든 이유(물론 현재도 걱정할 수준으로 포획이 진행되고 있기는 하지만 몇 십년 전 부흥기에 비하면 굉장한 수치로 줄어들었다고 한다)는 무엇일까?

포획이 줄어든 이유는 포획금지조약이 아닌 고래에서 구할 수 있는 고래 기름과 고래 수염 등을 대체할 수 있는 식물성 기름과 플라스틱, 등유가 생산되어 이를 대체하였기 때문이라고 한다.

역사적으로 보면 나무에서 석탄, 고래 기름에서 석유, 석탄에서 석유로의 에너지 전환이 이루어졌다.

하지만 이는 에너지원이 희귀해짐에 따라 혁신이 촉진된 것이 아니라 새로운 에너지 수요가 증가하였기 때문이라고 본다.

석유가 바이오 연료를 이긴 것은 궁극적으로 에너지 밀도가 대단히 높기 때문이다.

따라서 기술의 발전으로 인한 기름, 플라스틱, 석유 등의 생산은 환경에 해로운 영향만 끼치는 것이 아니라는 점이다.

그렇다면 현대 인간이 가장 많이 사용하는 에너지인 전기를 가장 안정적으로 생산하는 방법은 무엇일까?

안정적이라는 단어로 인해 많은 사람들의 머리 속에서 원자력을 떠올리긴 어렵겠지만 전기를 가장 안정적으로 생산하는 방법은 원자력이라고 한다.

원자를 쪼개서 열을 발생시키는 핵분열 방식은 불을 붙여 분자를 화학적으로 분해하는 방식보다 연료가 훨씬 적게 든다. 

따라서 천연가스나 석탄 발전 전기보다 훨씬 싼 가격에 공급된다.

건설에 비용이 다른 발전보다 더 많이 소요된다고 하더라도 긴 시간 계획적으로 가동하므로 장기적인 관점에서는 비용도 장점이 많다.

단, 건설에 반대하는 단체에 의해 건설이 지연될수록 비용이 가파르게 증가하는 단점이 있다.

원자력 에너지는 신재생 에너지보다 효율이 좋으며 탄소 배출 제로 에너지원이다.

태양광, 풍력과 달리 원자력은 전기 뿐만 아니라 열도 공급할 수 있으므로 난방, 취사, 수송같은 분야에서도 화석 연료를 대체할 수 있는 잠재력이 있다.

그러나 반핵 운동가에 의해 대중의 공포가 자라나고 과학적 연구와 기술적 탐구는 대학과 정부의 연구실을 벗어나지 못했다는 아쉬움이 있다.

20여년 간 핵무기의 공포를 학습하며 자란 세대가 구체적인 위험이 무엇인지도 모르면서 잘못된 정보만을 퍼트리고 있는 실정이라고 한다.

환경주의자는 에너지 효율을 높이고 절약하는 것으로 전기 소비를 줄일 수 있다고 말하지만 실제로 효율을 높인다고 해서 수요가 줄어들지는 않는다. 

또한 반핵운동가는 여전히 신재생 에너지가 존재하므로 원자력이 필요하지 않다고 주장한다.

하지만 원자력 발전소가 없으면 환경 오염의 주범이 되는 화석 연료 발전소가 반드시 필요해진다는 것을 기억해야 한다. 

산업혁명은 석탄의 에너지 밀도가 나무보다 훨씬 높기 때문에 가능했다.

같은 원리로 에너지 밀도가 훨씬 낮은 태양광과 풍력만으로는 오늘날의 고에너지 도시 산업 사회와 문명을 지탱할 수 없다.

 과학이 입증하는 사실이 아니라 자연에 대한 직관적인 견해에 근거해 환경 문제를 둘러싼 다양한 행동, 기술, 정책이 생기는데, 이런 직관적인 견해는 자연적인 것이 좋다는 오류에 빠지기 쉽다고 한다.

거북 껍질, 상아, 야생 어류, 유기농 비료, 나무 연료, 태양광 발전 등을 자연의 산물로 여기고 이런 자연적인 것이 화석 연료에서 추출한 플라스틱, 양식 어류, 화학 비료, 원자력 발전소와 같이 인공적인 것보다 더 친환경적이며 무작정 인류에게 좋다고 생각하는 것은 잘못된 것이다.

인공적인 것 역시 자연적인 것만큼이나 자연적이다.

다만 상대적으로 최근에 만들어졌을 뿐이다. 

신재생 에너지와 유기농이 자연과 풍광에 더 큰 해를 끼친다는 것을 입증하는 증거가 수없이 많지만 사실을 받아들이고 싶어 하지 않는 환경 운동가들이 많다. 

에너지 밀도는 환경에 대한 피해를 좌우하는 핵심 요소다.

천연가스는 석탄을 대체할 때는 좋은 연료지만 우라늄의 자리를 뺏으면 나쁜 연료가 된다.

조금 더 과학과 사실에 기반하여 환경에 대해 생각하고 무엇이 사람과 환경을 위한 것인지는 누구나 한 번쯤 생각해보면 좋을 내용인 것 같다.

책이 두꺼워서 생각할 시간도 많을 것 같다.

맥 OS(M1)에서 mongoDB 설치(zsh: command not found: mongo 해결)

zsh에 환경변수 설정하기

brew가 설치되어 있는 상황에서 진행합니다.

혹시 설치가 되어 있지 않은 경우에는 ‘M1 homebrew’를 검색하면 많은 안내 자료가 나오므로 참고하시면 됩니다.

먼저 설치 가능한 리스트를 확인합니다.

$ brew search mongodb

위 명령어를 실행하면 다음과 같은 리스트를 확인할 수 있습니다.

tap 명령어를 사용하면 더 많은 리스트를 확인할 수 있습니다.

$ brew tap mongodb/brew

그리고 다시 brew search mongodb를 실행하면 더 확장된 것을 볼 수 있습니다.

여기서 원하는 버전을 선택해서 설치를 진행하면 됩니다.

4.2 버전을 설치하도록 해보겠습니다.

$ brew install mongodb-community@4.2

설치가 완료되었으니 먼저 start로 몽고DB를 시작해 보겠습니다.

$ brew services start mongodb/brew/mongodb-community@4.2

Successfully started 메시지가 나오면 성공입니다.

이제 DB에 접속하기 위해 mongo를 입력해 보겠습니다.

커맨드를 찾을 수 없다는 에러가 나오는데요.

위를 살펴보면 If you need to have~~~~~ 부분에서 처음 시작하는 자는 다음 명령어를 실행하라고 나옵니다.

$ echo 'export PATH="/opt/homebrew/opt/mongodb-community@4.2/bin:$PATH"' >> ~/.zshrc

실행하고 다시 mongo를 실행해도 같은 에러가 발생하는 경우가 있습니다.

이 때는 환경변수 설정만 하고 적용이 안된 상태라서 발생하는 문제인데요.

환경변수를 적용하기 위해 다음 명령어를 실행하면 해결됩니다.

$ source ~/.zshrc

그리고 실행하면 다음과 같이 접속되는 것을 확인할 수 있습니다.

만약 이 환경변수를 직접 수정하고 싶은 경우에는 에디터를 사용해 ~/.zshrc를 열면 됩니다.

vi 에디터를 사용해 zsh(Z shell)의 환경변수 파일을 열어보겠습니다.

$ vi ~/.zshrc

앞에서 설정한 path가 들어있는 것을 볼 수 있습니다.

여기에 원하는 환경변수를 입력하거나 수정하고 저장(ESC + :wq + ENTER)해주시면 됩니다.

그리고 꼭! source ~/.zshrc를 사용해 변경을 적용을 해줘야 환경변수가 작동하므로 참고해주세요!

Address – Dwight D. Eisenhower [Atoms for Peace], 1953

Members of the General Assembly,

When Secretary General Hammarskjold’s invitation
to address this General Assembly reached me in Bermuda,
I was just beginning a series of conferences
with the prime Ministers and Foreign Ministers
of the United Kingdom and France.
Our subject was some of the problems that beset our world.
During the remainder of the Bermuda Conference,
I had constantly in mind that ahead of me lay a great honor.
That honor is mine today as I stand here,
privileged to address the General Assembly of the United Nations.

At the same time that I appreciate the distinction of addressing you,
I have a sense of exhilaration as I look upon this Assembly.
Never before in history has so much hope for so many people
been gathered together in a single organization.
Your deliberations and decisions during these somber years
have already realized part of those hopes.

But the great tests and the great accomplishments still lie ahead.
And in the confident expectation of those accomplishments,
I would use the office which, for the time being, I hold, to assure you
that the Government of the United States will remain steadfast in its support of this body.
This we shall do in the conviction that you will provide a great share of the wisdom,
of the courage and of the faith which can bring to this world lasting peace for all nations,
and happiness and well-being for all men.

Clearly, it would not be fitting for me to take this occasion to present to you
a unilateral American report on Bermuda.
Nevertheless, I assure you that in our deliberations on that lovely island
we sought to invoke those same great concepts of universal peace and human dignity
which are so clearly etched in your Charter.
Neither would it be a measure of this great opportunity merely to recite,
however hopefully, pious platitudes.
I therefore decided that this occasion warranted my saying to you some of the things
that have been on the minds and hearts of my legislative and executive associates,
and on mine, for a great many months.
thoughts I had originally planned to say primarily to the American people.

I know that the American people share my deep belief that
if a danger exists in the world, it is a danger shared by all.
And equally, that if hope exists in the mind of one nation,
that hope should be shared by all.
Finally, if there is to be advanced any proposal designed to ease
even by the smallest measure the tensions of today’s world,
what more appropriate audience could there be than the members
of the General Assembly of the United Nations.

I feel impelled to speak today in a language that in a sense is new, one which I,
who have spent so much of my life in the military profession, would have preferred never to use.
That new language is the language of atomic warfare.

The atomic age has moved forward at such a pace that every citizen of the world should have some comprehension,
at least in comparative terms, of the extent of this development,
of the utmost significance to every one of us.
Clearly, if the peoples of the world are to conduct an intelligent search for peace,
they must be armed with the significant facts of today’s existence.

My recital of atomic danger and power is necessarily stated in United States terms,
for these are the only incontrovertible facts that I know,
I need hardly point out to this Assembly, however,
that this subject is global, not merely national in character.

On 16 July 1945, the United States set off the world’s first atomic explosion.
Since that date in 1945, the United States of America has conducted forty-two test explosions.
Atomic bombs today are more than twenty-five times as powerful as the weapons
with which the atomic age dawned, while hydrogen weapons are in the ranges
of millions of tons of TNT equivalent.

Today, the United States stockpile of atomic weapons, which, of course increases daily,
exceeds by many times the total equivalent of the total of all bombs and all shells
that came from every plane and every gun in every theatre of war in all the years of the World War 2.
A single air group whether afloat or land based, can now deliver to any reachable target
a destructive cargo exceeding in power all the bombs that fell on Britain in all the World War 2.

In size and variety, the development of atomic weapons has been no less remarkable.
The development has been such that atomic weapons have virtually achieved conventional status
within our armed services.
In the United States, the Army, the Navy, the Air Force and the Marine Corps
are all capable of putting this weapon to military use.

But the dread secret and the fearful engines of atomic might are not ours alone.

In the first place, the secret is possessed by our friends and allies,
the Great Britain and Canada,
whose scientific genius made a tremendous contribution to our original discoveries
and the designs of atomic bombs.

The secret is also known by the Soviet Union.
The Soviet Union has informed us that, over recent years,
it has devoted extensive resources to atomic weapons.
During this period the Soviet Union has exploded a series of atomic devices,
including at least one involving thermo-nuclear reactions.

If at one time the United States possessed what might have been called a monopoly of atomic power,
that monopoly ceased to exist several years ago.
Therefore, although our earlier start has permitted us to accumulate
what is today a great quantitative advantage,
the atomic realities of today comprehend two facts of even greater significance.
First, the knowledge now possessed by several nations will eventually be shared
by others, possibly all others.

Second, even a vast superiority in numbers of weapons,
and a consequent capability of devastating retaliation, is no preventive, of itself,
against the fearful material damage and toll of human lives that would be inflicted by surprise aggression.

The free world, at least dimly aware of these facts,
has naturally embarked on a large program of warning and defense systems.
That program will be accelerated and extended.
But let no one think that the expenditure of vast sums for weapons and systems of defense
can guarantee absolute safety for the cities and citizens of any nation.
The awful arithmetic of the atomic bomb doesn’t permit of any such easy solution.
Even against the most powerful defense, an aggressor in possession
of the effective minimum number of atomic bombs for a surprise attack could probably
place a sufficient number of his bombs on the chosen targets to cause hideous damage.

Should such an atomic attack be launched against the United States,
our reactions would be swift and resolute.
But for me to say that the defense capabilities of the United States are such that
they could inflict terrible losses upon an aggressor, for me to say that
the retaliation capabilities of the United States are so great that such an aggressor’s land
would be laid waste, all this, while fact, is not the true expression of the purpose
and the hopes of the United States.

To pause there would be to confirm the hopeless finality of a belief
that two atomic colossi are doomed malevolently to eye each other indefinitely across a trembling world.
To stop there would be to accept helplessly the probability of civilization destroyed,
the annihilation of the irreplaceable heritage of mankind handed down to us
from generation to generation,
and the condemnation of mankind to begin all over again the age-old struggle upward
from savagery towards decency, and right, and justice.
Surely no sane member of the human race could discover victory in such desolation.
Could anyone wish his name to be coupled by history with such human degradation and destruction?
Occasional pages of history do record the faces of the “great destroyers”,
but the whole book of history reveals mankind’s never-ending quest for peace
and mankind’s God-given capacity to build.

It is with the book of history, and not with isolated pages,
that the United States will ever wish to be identified.
My country wants to be constructive, not destructive.
It wants agreements, not wars, among nations.
It wants itself to live in freedom and in the confidence
that the peoples of every other nation enjoy equally the right of choosing their own way of life.

So my country’s purpose is to help us to move out of the dark chamber of horrors into the light,
to find a way by which the minds of men, the hopes of men, the souls of men everywhere,
can move forward towards peace and happiness and well-being.

In this quest, I know that we must not lack patience.
I know that in a world divided, such as ours today, salvation cannot be attained by one dramatic act.
I know that many steps will have to be taken over many months
before the world can look at itself one day and truly realize
that a new climate of mutually peaceful confidence is abroad in the world.
But I know, above all else, that we must start to take these steps – now.

The United States and its allies, the United Kingdom and France,
have over the past months tried to take some of these steps.
Let no one say that we shun the conference table.
On the record has long stood the request of the United States,
the United Kingdom and France to negotiate with the Soviet Union the problems of a divided Germany.
On that record has long stood the request of the same three nations
to negotiate an Austrian peace treaty.
On the same record still stands the request of the United Nations
to negotiate the problems of Korea.

Most recently we have received from the Soviet Union
what is in effect an expression of willingness to hold a four-Power meeting.
Along with our allies, the United Kingdom and France, we were pleased to see
that this note did not contain the unacceptable pre-conditions previously put forward.
As you already know from our joint Bermuda communique, the United States,
the United Kingdom and France have agreed promptly to meet with the Soviet Union.

The Government of the United States approaches this conference with hopeful sincerity.
We will bend every effort of our minds to the single purpose of emerging
from that conference with tangible results towards peace,
the only true way of lessening international tension.

We never have, and never will, propose or suggest that the Soviet Union surrender
what rightly belongs to it.
We will never say that the peoples of the USSR are an enemy with whom
we have no desire ever to deal or mingle in friendly and fruitful relationship.

On the contrary, we hope that this coming conference may initiate a relationship
with the Soviet Union which will eventually bring about a freer mingling of the peoples
of the East and of the West – the one sure, human way of developing the understanding required
for confident and peaceful relations.

Instead of the discontent which is now settling upon Eastern Germany,
occupied Austria and the countries of Eastern Europe,
we seek a harmonious family of free European nations,
with none a threat to the other, and least of all a threat to the peoples of the USSR.
Beyond the turmoil and strife and misery of Asis,
we seek peaceful opportunity for these peoples to develop their natural resources and to elevate their lot.

These are not idle words or shallow visions.
Behind them lies a story of nations lately come to independence,
not as a result of war, but through free grant or peaceful negotiation.
There is a record already written of assistance gladly given by nations of the West
to needy peoples and to those suffering the temporary effects of famine, drought and natural disaster.
These are deeds of peace.
They speak more loudly than promises or protestations of peaceful intent.

But I do not wish to rest either upon the reiteration of past proposals or the restatement of past deeds.
The gravity of the time is such that every new avenue of peace,
no matter how dimly discernible, should be explored.

There is at least one new avenue of peace which has not been well explored.
An avenue now laid out by the General Assembly of the United Nations.

In its resolution of 28 November 1953 (resolution 715 (VIII)) this General Assembly suggested.
that the Disarmament Commission study the desirability of establishing
a sub-committee consisting of representatives of the Powers principally involved,
which should seek in private an acceptable solution and report
on such a solution to the General Assembly
and to the Security Council not later than 1 September 1954.

The United States, heeding the suggestion of the General Assembly of the United Nations,
is instantly prepared to meet privately with such other countries as may be “principally involved”,
to seek “an acceptable solution” to the atomic armaments race
which overshadows not only the peace, but the very life, of the world.

We shall carry into these private or diplomatic talks a new conception.
The United States would seek more than the mere reduction
or elimination of atomic materials for military purposes.
It is not enough to take this weapon out of the hands of the soldiers.
It must be put into the hands of those who will know how to strip
its military casing and adapt it to the arts of peace.

The United States knows that if the fearful trend of atomic military build-up can be reversed,
this greatest of destructive forces can be developed into a great boon, for the benefit of all mankind.
The United States knows that peaceful power from atomic energy is no dream of the future.
The capability, already proved, is here today.
Who can doubt that, if the entire body of the world’s scientists and engineers had adequate amounts
of fissionable material with which to test and develop their ideas,
this capability would rapidly be transformed into universal, efficient and economic usage?

To hasten the day when fear of the atom will begin to disappear from the minds
the people and the governments of the East and West,
there are certain steps that can be taken now.

I therefore make the following proposal.

The governments principally involved, to the extent permitted by elementary prudence,
should begin now and continue to make joint contributions from their stockpiles
of normal uranium and fissionable materials to an international atomic energy agency.
We would expect that such an agency would be set up under the aegis of the United Nations.
The ratios of contributions, the procedures and other details would properly be within the scope
of the private conversations I referred to earlier.

The United States is prepared to undertake these explorations in good faith.
Any partner of the United States acting in the same good faith will find the United States
a not unreasonable or ungenerous associate.

Undoubtedly, initial and early contributions to this plan would be small in quantity.
However, the proposal has the great virtue that it can be undertaken without the irritations
and mutual suspicions incident to any attempt to set up a completely acceptable system
of world-wide inspection and control.

The atomic energy agency could be made responsible for the impounding,
storage and protection of the contributed fissionable and other materials.
The ingenuity of our scientists will provide special safe conditions under which
such a bank of fissionable material can be made essentially immune to surprise seizure.

The more important responsibility of this atomic energy agency would be to devise methods
whereby this fissionable material would be allocated to serve the peaceful pursuits of mankind.
Experts would be mobilized to apply atomic energy to the needs of agriculture,
medicine and other peaceful activities.
A special purpose would be to provide abundant electrical energy
in the power-starved areas of the world.

Thus the contributing Powers would be dedicating some of their strength
to serve the needs rather than the fears of mankind.

The United States would be more than willing.
It would be proud to take up with others principally involved.
The development of plans whereby such peaceful use of atomic energy would be expedited.

Of those principally involved the Soviet Union must, of course, be one.

I would be prepared to submit to the Congress of the United States,
and with every expectation of approval, any such plan that would.
First, encourage world-wide investigation into the most effective peacetime uses of fissionable material,
and with the certainty that the investigators had all the material needed for the conducting
of all experiments that were appropriate.
Second, begin to diminish the potential destructive power of the world’s atomic stockpiles.
Third, allow all peoples of all nations to see that, in this enlightened age,
the great Powers of the earth, both of the East and of the West,
are interested in human aspirations first rather than in building up the armaments of war.
Fourth, open up a new channel for peaceful discussion and initiative
at least a new approach to the many difficult problems that must be solved
in both private and public conversations if the world is to shake off the inertia
imposed by fear and is to make positive progress towards peace.

Against the dark background of the atomic bomb, the United States does not wish merely
to present strength, but also the desire and the hope for peace.
The coming months will be fraught with fateful decisions.
In this Assembly, in the capitals and military headquarters of the world,
in the hearts of men everywhere, be they governed or governors,
may they be the decisions which will lead this world out of fear and into peace.

To the making of these fateful decisions, the United States pledges before you,
and therefore before the world, its determination to help solve the fearful atomic dilemma
to devote its entire heart and mind to finding the way by which the miraculous inventiveness of man
shall not be dedicated to his death, but consecrated to his life.

I again thank representatives for the great honor they have done me
in inviting me to appear before them and in listening to me so graciously.

자바스크립트 배열+반복문의 속도 테스트(map, for, while, for…in, for…of)

반복문의 배열 작업 속도를 확인하기

배열 관련하여 각 요소별로 순회하는 반복문 작업을 할 때 가장 익숙한 방법을 사용하거나 때로는 가장 먼저 떠오르는 방법을 사용하기도 합니다.

배열의 크기가 작으면 상관이 없지만 배열의 크기가 커지면 작은 차이가 큰 차이를 만들어낼 수 있습니다.

문득 연산 속도가 가장 빠른 반복문이 무엇일까라는 궁금증이 생겨 간단하게 하나의 배열 데이터를 다른 배열로 옮기는 연산을 통해 속도를 테스트해보고자 합니다.

크기에 상관없이 반복문 별로 같은 효율을 보여주리라 생각했지만 배열의 크기에 따라 각각 다른 속도를 보여주는 점이 흥미로웠습니다.


1. 테스트 방법

먼저 일정 크기를 갖는 배열 array을 생성합니다.

console.time 메서드를 사용해 이 배열의 데이터를 다른 배열로 복사하는 작업을 진행하고 이 작업 시간을 측정합니다.

테스트는 map, for, while, for…in, for…of의 다섯 가지 반복문을 사용합니다.

// 배열 데이터 생성
const array = [];
for(let i=0;i<10000;i++){
  array.push(i);
}

// 데이터가 복사될 배열
let arraymap = [];

console.time('map');  //타이머 시작
arraymap = array.map(list=>list);
console.timeEnd('map'); //타이머 종료

위와 같은 방식으로 3회씩 테스트를 진행하며 배열의 크기를 조절하여 반복문 별로 상대적인 작업 속도의 변화를 확인합니다.


2. 테스트

먼저 배열의 크기가 아주 작을 때는 모두 큰 차이를 보이지 않습니다.

다음은 배열의 크기가 100일 때 결과입니다.

작업을 세 번 진행한 결과 map과 for…of가 엎치락뒤치락하지만 항상 가장 빠른 속도를 보여줍니다.

for, while, for…in도 세번 모두 결과가 엎치락뒤치락하지만 위의 두 반복문보단 느린 속도를 보여줍니다.

그럼 배열의 크기를 1000으로 올려보겠습니다.

크기가 1000일 때는 대체적으로 비슷한 속도를 보여줍니다.

for…in만 다른 반복문보다 느린 것이 확인됩니다.

이제 확연하게 유의미한 차이를 느낄 수 있는 크기인 10000으로 올려보겠습니다.

10000에서는 map이 가장 우수한 속도를 보여줍니다.

눈에 띄는 부분은 작은 사이즈에서는 map과 대등한 속도를 보이던 for…of가 여기서는 가장 느린 속도를 기록합니다.

또한 for…in은 오히려 for…of보다 빠른 속도를 보여줍니다.

그럼 1000000으로 확인해 보겠습니다.

배열이 매우 커지니 작업 속도는 for문이 가장 준수합니다.

map, while도 큰 차이를 보이지 않고 준수한 성능을 보여줍니다.

for…of는 확연하게 조금 느린 속도를 보여주고 for…in은 이제 인사를 해야할 것 같습니다.

그럼 마지막으로 10000000(천만)으로 테스트를 해보겠습니다.

세 번 테스트한 결과 모두 for 문이 가장 빠른 속도를 보여주었으며, map, while도 의미있는 속도를 보여줍니다.

확실히 for…of는 위의 세 반복문보다 느린 속도를 보여주었으며 for…in은 10배가 넘는 느린 속도의 차이를 보여줍니다.


3. 결과 정리

배열 테이터의 크기가 작을 때는 의미있는 차이가 없지만 배열이 커질수록 map, for, while의 속도가 우수하고 for…in, for…of는 속도 저하를 보이는 결과를 나타냅니다.

어디까지나 단순한 작업인 배열 데이터 복사 기능만을 사용한 테스트이므로 작업 내용에 따라 다른 결과를 보일 가능성이 있어 단순 참고용으로 삼으면 좋을 것 같습니다.

다음은 테스트에 사용한 코드 전체입니다.

console.log('-------------start----------------')

const array = [];

for(let i=0;i<10000;i++){  //크기 변경
	array.push(i);
}

console.log("arraysize:"+array.length);
console.log('--------------------------------');

let arraymap = [];

console.log('arraymap start:'+arraymap.length);
console.time('map');

arraymap = array.map(list=>list);

console.log('arraymap end:'+arraymap.length);
console.timeEnd('map');
console.log('--------------------------------');


let arrayfor = [];
console.log('arrayfor start:'+arrayfor.length);
console.time('for');

for(let i=0; i<array.length;i++){
	arrayfor.push(array[i]);
};

console.log('arrayfor end:'+arrayfor.length);
console.timeEnd('for');
console.log('--------------------------------');

let arraywhile = [];
let whilenum = 0;
console.log('arraywhile start:'+arraywhile.length);
console.time('while');

while(whilenum<array.length){
	arraywhile.push(array[whilenum]);
	whilenum++;
};

console.log('arraywhile end:'+arraywhile.length);
console.timeEnd('while');
console.log('--------------------------------');

const arrayforof = [];
console.log('arrayforof start:'+arrayforof.length);
console.time('forof');

for(const num of array){
	arrayforof.push(num)
};

console.log('arrayfor end:'+arrayforof.length);
console.timeEnd('forof');
console.log('--------------------------------');

let arrayforin = [];
console.log('arrayforin start:'+arrayforin.length);
console.time('forin');

for(const num in array){
	arrayforin.push(array[num]);
};

console.log('arrayforin end:'+arrayforin.length);
console.timeEnd('forin');


console.log('---------------end-----------------');

MongoDB, lean을 사용한 속도 개선(mongoose)

쿼리에 lean() 추가를 통한 성능 개선

몽구스(mongoose) 쿼리의 리턴값은 Document 클래스의 인스턴스입니다.

이 인스턴스는 많은 state를 갖고 있어 다양한 작업이 가능하게 합니다.

.get(), .set(), .save(), toObject(), toJSON() 등 리턴값에 대해 여러 메서드 사용이 가능하고 이 결과로 다시 쿼리를 진행할 수 있습니다.

하지만 단지 결과 데이터만 목적으로 하는 find() 같은 작업은 다른 정보나 메서드를 사용하지 않습니다.

이 때 lean()을 유용하게 사용할 수 있습니다.

쿼리에 lean()을 추가하면 인스턴스가 아닌 POJO(Plain Old Javascript Object)를 리턴합니다.

따라서 필요 없는 데이터를 함께 반환하지 않으니 속도와 메모리 부분에서 큰 장점을 발휘합니다.

샘플 코드를 통해 결과를 확인해 보겠습니다.

import sizeof from 'object-sizeof';

const query = {'status':1};
const lean = await Product.find(query).lean();
const normal = await Product.find(query).exec();

console.log('lean: '+sizeof(lean));
console.log('-----------');
console.log('normal: '+sizeof(normal));

위에서 lean과 normal의 크기를 비교한 결과는 다음과 같습니다.

lean 하나로 객체의 사이즈가 약 10배가 넘게 차이 나는 결과가 발생합니다.

하지만 lean을 사용한 결과값은 .save(), .get() 등의 사용이 불가하니 필요에 따라서 사용해야 하는 점을 유의해야 합니다.

Faster Mongoose Queries With Lean



성능 개선은 뛰어난 안목과 분석력이 있어야만 가능한 것이 아니라 작은 부분 하나하나가 만들어내는 차이를 쌓아가는 부분이라고 생각합니다.

Address – Steve Jobs Stanford 2005

I am honored to be with you today at your commencement.
from one of the finest universities in the world.
I never graduated from college.
Truth be told, this is the closest I’ve ever gotten to a college graduation.
Today I want to tell you three stories from my life.
That’s it.
No big deal.
Just three stories.

The first story is about connecting the dots.

I dropped out of Reed College after the first 6 months,
but then stayed around as a drop-in for another 18 months or so before I really quit.
So why did I drop out?

It started before I was born.
My biological mother was a young, unwed college graduate student,
and she decided to put me up for adoption.
She felt very strongly that I should be adopted by college graduates,
so everything was all set for me to be adopted at birth by a lawyer and his wife.
Except that when I popped out they decided at the last minute that they really wanted a girl.
So my parents, who were on a waiting list, got a call in the middle of the night asking.
“We have an unexpected baby boy. do you want him?”
They said “Of course”.
My biological mother later found out that my mother had never graduated from college
and that my father had never graduated from high school.
She refused to sign the final adoption papers.
She only relented a few months later when my parents promised that I would someday go to college.

And 17 years later I did go to college.
But I naively chose a college that was almost as expensive as Stanford,
and all of my working-class parents’ savings were being spent on my college tuition.
After six months, I couldn’t see the value in it.
I had no idea what I wanted to do with my life
and no idea how college was going to help me figure it out.
And here I was spending all of the money my parents had saved their entire life.
So I decided to drop out and trust that it would all work out OK.
It was pretty scary at the time, but looking back it was one of the best decisions I ever made.
The minute I dropped out I could stop taking the required classes
that didn’t interest me, and begin dropping in on the ones that looked interesting.

It wasn’t all romantic.
I didn’t have a dorm room, so I slept on the floor in friends’ rooms,
I returned Coke bottles for the 5¢ deposits to buy food with,
and I would walk the 7 miles across town every Sunday night
to get one good meal a week at the Hare Krishna temple.
I loved it.
And much of what I stumbled into by following my curiosity
and intuition turned out to be priceless later on. Let me give you one example.

Reed College at that time offered perhaps the best calligraphy instruction in the country.
Throughout the campus every poster, every label on every drawer, was beautifully hand calligraphed.
Because I had dropped out and didn’t have to take the normal classes,
I decided to take a calligraphy class to learn how to do this.
I learned about serif and sans serif typefaces,
about varying the amount of space between different letter combinations,
about what makes great typography great.
It was beautiful, historical, artistically subtle in a way
that science can’t capture, and I found it fascinating.

None of this had even a hope of any practical application in my life.
But 10 years later, when we were designing the first Macintosh computer, it all came back to me.
And we designed it all into the Mac.
It was the first computer with beautiful typography.
If I had never dropped in on that single course in college,
the Mac would have never had multiple typefaces or proportionally spaced fonts.
And since Windows just copied the Mac, it’s likely that no personal computer would have them.
If I had never dropped out, I would have never dropped in on this calligraphy class,
and personal computers might not have the wonderful typography that they do.
Of course it was impossible to connect the dots looking forward when I was in college.
But it was very, very clear looking backward 10 years later.

Again, you can’t connect the dots looking forward.
you can only connect them looking backward.
So you have to trust that the dots will somehow connect in your future.
You have to trust in something.
your gut, destiny, life, karma, whatever.
This approach has never let me down, and it has made all the difference in my life.

My second story is about love and loss.

I was lucky — I found what I loved to do early in life.
Woz and I started Apple in my parents’ garage when I was 20.
We worked hard, and in 10 years Apple had grown from just the two of us
in a garage into a $2 billion company with over 4,000 employees.
We had just released our finest creation, the Macintosh, a year earlier, and I had just turned 30.
And then I got fired.
How can you get fired from a company you started?
Well, as Apple grew we hired someone who I thought was very talented
to run the company with me, and for the first year or so things went well.
But then our visions of the future began to diverge and eventually we had a falling out.
When we did, our Board of Directors sided with him.
So at 30 I was out.
And very publicly out.
What had been the focus of my entire adult life was gone, and it was devastating.

I really didn’t know what to do for a few months.
I felt that I had let the previous generation of entrepreneurs down 
that I had dropped the baton as it was being passed to me.
I met with David Packard and Bob Noyce and tried to apologize for screwing up so badly.
I was a very public failure, and I even thought about running away from the valley.
But something slowly began to dawn on me, I still loved what I did.
The turn of events at Apple had not changed that one bit.
I had been rejected, but I was still in love.
And so I decided to start over.

I didn’t see it then, but it turned out that getting fired from Apple was
the best thing that could have ever happened to me.
The heaviness of being successful was replaced
by the lightness of being a beginner again, less sure about everything.
It freed me to enter one of the most creative periods of my life.

During the next five years, I started a company named NeXT,
another company named Pixar,
and fell in love with an amazing woman who would become my wife.
Pixar went on to create the world’s first computer animated feature film, Toy Story,
and is now the most successful animation studio in the world.
In a remarkable turn of events, Apple bought NeXT, I returned to Apple,
and the technology we developed at NeXT is at the heart of Apple’s current renaissance.
And Laurene and I have a wonderful family together.

I’m pretty sure none of this would have happened if I hadn’t been fired from Apple.
It was awful tasting medicine, but I guess the patient needed it.
Sometimes life hits you in the head with a brick.
Don’t lose faith.
I’m convinced that the only thing that kept me going was that I loved what I did.
You’ve got to find what you love.
And that is as true for your work as it is for your lovers.
Your work is going to fill a large part of your life,
and the only way to be truly satisfied is to do what you believe is great work.
And the only way to do great work is to love what you do.
If you haven’t found it yet, keep looking.
Don’t settle.
As with all matters of the heart, you’ll know when you find it.
And, like any great relationship, it just gets better and better as the years roll on.
So keep looking until you find it. Don’t settle.

My third story is about death.

When I was 17, I read a quote that went something like
“If you live each day as if it was your last, someday you’ll most certainly be right.”
It made an impression on me, and since then, for the past 33 years,
I have looked in the mirror every morning and asked myself.
“If today were the last day of my life, would I want to do what I am about to do today?”
And whenever the answer has been “No” for too many days in a row,
I know I need to change something.

Remembering that I’ll be dead soon is the most important tool
I’ve ever encountered to help me make the big choices in life.
Because almost everything, all external expectations, all pride,
all fear of embarrassment or failure,
these things just fall away in the face of death, leaving only what is truly important.
Remembering that you are going to die is the best way I know
to avoid the trap of thinking you have something to lose.
You are already naked.
There is no reason not to follow your heart.

About a year ago I was diagnosed with cancer.
I had a scan at 7:30 in the morning, and it clearly showed a tumor on my pancreas.
I didn’t even know what a pancreas was.
The doctors told me this was almost certainly a type of cancer that is incurable,
and that I should expect to live no longer than three to six months.
My doctor advised me to go home and get my affairs in order,
which is doctor’s code for prepare to die.
It means to try to tell your kids everything you thought
you’d have the next 10 years to tell them in just a few months.
It means to make sure everything is buttoned up
so that it will be as easy as possible for your family.
It means to say your goodbyes.

I lived with that diagnosis all day.
Later that evening I had a biopsy, where they stuck an endoscope down my throat,
through my stomach and into my intestines,
put a needle into my pancreas and got a few cells from the tumor.
I was sedated, but my wife, who was there, told me
that when they viewed the cells under a microscope the doctors started crying
because it turned out to be a very rare form of pancreatic cancer
that is curable with surgery.
I had the surgery and I’m fine now.

This was the closest I’ve been to facing death,
and I hope it’s the closest I get for a few more decades.
Having lived through it, I can now say this to you with a bit more certainty
than when death was a useful but purely intellectual concept:

No one wants to die.
Even people who want to go to heaven don’t want to die to get there.
And yet death is the destination we all share.
No one has ever escaped it.
And that is as it should be, because Death is very likely the single best invention of Life.
It is Life’s change agent.
It clears out the old to make way for the new.
Right now the new is you, but someday not too long from now,
you will gradually become the old and be cleared away.
Sorry to be so dramatic, but it is quite true.

Your time is limited, so don’t waste it living someone else’s life.
Don’t be trapped by dogma which is living with the results of other people’s thinking.
Don’t let the noise of others’ opinions drown out your own inner voice.
And most important, have the courage to follow your heart and intuition.
They somehow already know what you truly want to become.
Everything else is secondary.

When I was young, there was an amazing publication
called The Whole Earth Catalog, which was one of the bibles of my generation.
It was created by a fellow named Stewart Brand not far from here in Menlo Park,
and he brought it to life with his poetic touch.
This was in the late 1960s, before personal computers and desktop publishing,
so it was all made with typewriters, scissors and Polaroid cameras.
It was sort of like Google in paperback form, 35 years before Google came along.
It was idealistic, and overflowing with neat tools and great notions.

Stewart and his team put out several issues of The Whole Earth Catalog,
and then when it had run its course, they put out a final issue.
It was the mid 1970s, and I was your age.
On the back cover of their final issue was a photograph of an early morning country road,
the kind you might find yourself hitchhiking on if you were so adventurous.
Beneath it were the words.
‘Stay Hungry. Stay Foolish.’
It was their farewell message as they signed off.
Stay Hungry. Stay Foolish.
And I have always wished that for myself.
And now, as you graduate to begin anew, I wish that for you.

Stay Hungry. Stay Foolish.

Thank you all very much.

[BOOK] 세상에서 가장 행복한 100세 노인

사람답게 살기 위한 한 달에 한 권(2022/01)

서점에 들렀다가 눈길을 사로잡아 구매한 책.

1930년대 유럽과 독일에서 벌어진 홀로코스트를 소재로 한 영화와 소설이 참 많고 또 모든 게 다 슬픈 이야기지만 가만히 놓고 보면 사람의 차가운 잔혹성과 따뜻한 인정을 함께 다룬 것이 많다.

저자 또한 수용소에 끌려가 내일이 보이지 않는 삶을 살았지만 지나고보면 어제를 버티게 해준 것은 가족과 친구 그리고 오늘에 대한 희망이었다.

저자가 이야기하는 인생에서 가장 소중한 것 역시 저자를 버티게 해 준 세 가지로 요약할 수 있을 것 같다.

항상 내 인생에서도 최선이 되기를 바라는 세 가지다.

한 겨울 영하 8도. 아주 얇은 천 하나만 걸치고 서로의 온기로 한 밤을 지내는 사람들이 새벽에 화장실 갈 때마다 가장자리 사람이 얼어 죽지 않도록 안쪽으로 밀어주고 잠이 들지만 아침에 뜨는 해를 보지 못하는 사람이 많았다는 이야기는 너무 뇌리에 깊이 남아 잊혀지지 않을 것 같다.

또한 수용소에서 전기가 통하는 철장에 뛰어들어 스스로 생을 마감하거나 독재가 끝났지만 남은 가족이 없어 삶의 의미를 잃고 생을 마감한 사람들이 많다는 이야기도 몰랐던 사실이었다.

하지만 이런 슬픔의 시대를 지나오면서도 저자인 에디 제이쿠 할아버지는 희망을 놓지 않고 살았기에 오늘 우리가 표지 사진을 보면서 놀라워할 수 있지 않을까.

교육이 힘든 시기를 버티고 살아남을 수 있는 기회를 제공한 값진 보물이었다고 한다.

수용소에서 공학 기술 덕분에 죽음의 문턱에서 몇 번이나 살아남을 수 있었다고..

그는 그 후 과거에 지배당하지 않고 평생 행복하다고 이야기할 수 있는 삶을 살았다고 했다.

책을 보면서 더 자주 자신의 행복을 돌아볼 수 있는 사람이 될 수 있으면 어떨까하는 생각이 들었다.

줄무늬 파자마를 입은 소년, 책도둑, 피아니스트 그리고 인생은 아름다워가 생각나는 밤이다.

OnKeyPress는 왜 ESC가 인식이 안될까?(React.키 이벤트 처리)

Key 입력을 처리하는 속성

리액트 input에서 키 입력 이벤트를 처리할 때 onKeyPress, onKeyDown, onKeyUp 이벤트를 사용합니다.

자바스크립트와 같은 명칭의 속성들을 리액트는 camel case로 표기합니다.

다음과 같이 사용합니다.

const onKeyPress= e => {
    if(e.key==='Enter'){    
        findExecute();
    }   
}

........

<div onKeyPress={onKeyPress}>click</div>

이벤트가 발생하는 시점이 조금씩 다를 뿐 사용 방법은 같습니다.

그리고 각 이벤트 별 특징은 다음과 같습니다.

onKeyDown 👉 이벤트가 먼저 실행
onKeyUp 👉 text가 입력되면 실행
onKeyPress 👉 text 입력이 완료되면 실행 (Deprecated)

MDN의 공식 문서를 보면 이제 onKeyPress는 더 이상 사용되지 않는다고 하니 거의 비슷하게 동작하는 onKeyDown을 사용하는 것이 좋습니다.

MDN – keypress event


왜 onKeyPress에서 ESC가 동작하지 않을까?

onKeyPress는 기본적으로 ESC가 눌려졌을 때 이벤트가 생성되지 않기 때문입니다.

onKeyPress는 ESC, CTRL, ALT 등 function 기능을 갖는 키를 제외하고 알파벳과 숫자 키에서만 이벤트가 생성됩니다.

하지만 onKeyDown, onKeyUp은 onKeyPress에서 인식되지 기능 키들도 인식이 됩니다.

또한 onKeyPress는 이제 더 이상 지원되지 않는다고 하니 기본적으로는 onKeyDown을 사용하고 상황에 따라 onKeyUp을 사용하면 큰 문제 없이 원하는 방식으로 구현할 수 있을 것입니다.

각 키 값과 이슈 관련 페이지를 링크로 남기겠습니다.


키 코드를 직접 입력해보면서 알 수 있는 사이트 -> https://keycode.info/

관련 이슈 -> https://github.com/Leaflet/Leaflet/issues/5234

이진 탐색(binary search), 자바스크립트로 구현하기

이진 탐색과 구현방법

이진 탐색(binary search)은 데이터 집합에서 원하는 데이터를 찾을 때까지 집합을 이분(二分)하여 탐색하는 방법입니다.

데이터 집합을 둘로 나누고 찾는 데이터가 있는 집합을 선택하여 다시 반으로 나누고 다시 데이터가 있는 집합에 같은 과정을 계속 반복합니다.

따라서 아무리 큰 데이터라도 몇 번의 연산만으로 원하는 데이터를 찾을 수 있습니다.

하지만 이진 탐색은 조건이 있는데요.

데이터가 반드시 순서대로 정렬된 상태여야 합니다.

그림을 통해 탐색의 과정을 확인해 보겠습니다.

위와 같은 데이터 집합에서 2를 찾으려면 먼저 집합을 반으로 나누고 찾는 데이터가 속한 집합을 선택합니다.

그럼 첫 번째로 선택한 집합은 다음과 같습니다.

또 반을 나누고 2가 속한 집합만을 선택합니다.

여기서 반을 나누고 2가 속한 집합을 선택하면 다음과 같습니다.

이제 둘 중 하나를 확인하여 원하는 데이터를 선택하면 됩니다.

이진 탐색 코드는 다음과 같습니다.

const binarySearch=(target, data)=>{

  let low = 0;
  let high = data.length-1;
  
  while(low<=high){
    
    let mid = Math.floor((low+high)/2);    
  
    if(target===data[mid]){
       return mid;
    }else if(target>data[mid]){
      low = mid+1 
    }else if(target<data[mid]){
      high = mid-1
    }
  }

  return undefined;
}

이 탐색 방법은 데이터의 양이 많아지면 엄청난 효율을 자랑합니다.

데이터가 10000까지 있을 때 8000을 찾기 위해서 무차별 대입은 7999번의 연산을 진행해야 하지만 이진 탐색 방법은 13번의 연산이면 원하는 데이터를 찾을 수 있습니다.

자바스크립트를 이용한 BFS, DFS 구현하기(javascript)

데이터는 선형 구조(배열, 연결리스트, 스택, 큐) 또는 비선형 구조(트리, 그래프)로 이루어져 있으며, 순차적으로 나열된 선형 구조에 비해 비선형 구조의 데이터는 탐색이 어렵습니다.

하지만 비선형 구조의 대표적인 탐색 방법인 BFS, DFS를 사용하면 깔끔하게 탐색이 가능합니다.

두 방법 모두 무차별 탐색(Brute Force Search, 모든 데이터를 하나씩 탐색) 방법을 사용합니다.


DFS는 깊이 우선 탐색 방법으로 트리 구조의 데이터에서 노드마다 가장 깊이까지 탐색한 뒤 다음 노드로 이동하는 방법입니다.

위와 같은 트리 구조의 데이터가 있을 때, DFS는 한번 선택한 길은 끝까지 가본 뒤 다음 길을 탐색하는 방식과 같습니다.

그림으로 나타내면 다음과 같습니다.

검색 속도는 BFS에 비해서 느리지만 조금 더 간단합니다.

경로의 특징이 필요한 문제를 풀 때 DFS를 사용합니다.

const graph = {
  A: ["B", "C"],
  B: ["A", "D"],
  C: ["A", "E"],
  D: ["B", "F"],
  E: ["C","G"],
  F: ["D","H","I"],
  G: ["E","J","K"],
  H: ["F","L"],
  I: ["F", "M"],
  J: ["G","N"],
  K: ["G","O"],
  L: ["H"],
  M: ["I","P"],
  N: ["J"],
  O: ["K"],
  P: ["M"]
};

const bfs = (graph, start) => {

    const checked = [];    // 탐색 완료 데이터
    const willCheck = [];  // 탐색 예정 데이터
    
    willCheck.push(start);
    
    while(willCheck.length!==0){
      const node = willCheck.pop();  // 스택(Last In First Out)
      if(!checked.includes(node)){
       	 checked.push(node);
         //reverse() 제거 시 그림의 4,3,2,1 순서로 탐색     
      	 willCheck.push(...graph[node].reverse());  
        
      }
   }
	return checked;
}

console.log(bfs(graph, "A"));
// ['A', 'B', 'D', 'F', 'H', 'L', 'I', 'M', 'P', 'C', 'E', 'G', 'J', 'N', 'K', 'O']

BFS는 너비 우선 탐색 방법으로 트리 구조 데이터에서 노드의 인접 데이터를 모두 탐색한 뒤 다음 데이터로 이동하는 방법입니다.

그림으로 나타내면 다음과 같습니다.

탐색 속도는 DFS보다 빠르며 최단 거리를 구하는 문제에서 사용할 수 있습니다.

const graph = {
  A: ["B", "C"],
  B: ["A", "D"],
  C: ["A", "E"],
  D: ["B", "F"],
  E: ["C","G"],
  F: ["D","H","I"],
  G: ["E","J","K"],
  H: ["F","L"],
  I: ["F", "M"],
  J: ["G","N"],
  K: ["G","O"],
  L: ["H"],
  M: ["I","P"],
  N: ["J"],
  O: ["K"],
  P: ["M"]
};

const bfs = (graph, start) => {

    const checked = [];
    const willCheck = [];
    
    willCheck.push(start);
    
    while(willCheck.length!==0){
      const node = willCheck.shift(); // 큐(First In First Out)
      if(!checked.includes(node)){
       	 checked.push(node);
      	 willCheck.push(...graph[node]);       
      }
   }
	return checked;
}

console.log(bfs(graph, "A"));
// ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P']